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
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();
}
}
}