WebApi2: Custom parameter binding to bind partial parameters

前端 未结 1 1739
予麋鹿
予麋鹿 2021-02-03 14:34

I have a webApi2 project and an other project, in which I have my Model classes and a BaseModel that is a base for all Models, as following,

public class BaseMod         


        
相关标签:
1条回答
  • 2021-02-03 15:11

    Following is a quick example using HttpParameterBinding. Here I am creating a custom parameter binding where I let the default FromBody based binding to use the formatters to deserialize the request body and then I get the user id from request headers and set on the the deserialized object. (You might need to add additional validation checks on the following code).

    config.ParameterBindingRules.Insert(0, (paramDesc) =>
                {
                    if (typeof(BaseModel).IsAssignableFrom(paramDesc.ParameterType))
                    {
                        return new BaseModelParamBinding(paramDesc);
                    }
    
                    // any other types, let the default parameter binding handle
                    return null;
                });
    

    public class BaseModelParamBinding : HttpParameterBinding
    {
        HttpParameterBinding _defaultFromBodyBinding;
        HttpParameterDescriptor _paramDesc;
    
        public BaseModelParamBinding(HttpParameterDescriptor paramDesc)
            : base(paramDesc)
        {
            _paramDesc = paramDesc;
            _defaultFromBodyBinding = new FromBodyAttribute().GetBinding(paramDesc);
        }
    
        public override async Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
            HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            await _defaultFromBodyBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken);
    
            BaseModel baseModel = actionContext.ActionArguments[_paramDesc.ParameterName] as BaseModel;
    
            if (baseModel != null)
            {
                baseModel.UserId = actionContext.Request.Headers.GetValues("UserId").First();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题