6

我有一个 webApi2 项目和另一个项目,其中我有我的模型类和一个 BaseModel,它是所有模型的基础,如下所示,

public class BaseModel
{
    public string UserId { get; set; }
}

所有其他模型都来自我的 BaseModel。

在 webapi 我有我的 CustomerController 如下,

public class CustomerController : ApiController
{
    [HttpPost]
    public GetCustomerResponseModel Get(GetCustomerRequestModel requestModel)
    {
        var response = new GetCustomerResponseModel();

        //I need only the UserId coming from the BaseModel is binded from request headers
        var userId = requestModel.UserId;

        //I want all model data except UserId is binded with default model binding
        var customerData = requestModel.CustomerData;
        var someOtherData = requestModel.SomeOtherData;

        return response;
    }

    [HttpPost]
    public AddStockAlertResponseModel AddStockAlert(AddStockAlertRequestModel requestModel)
    {
        var response = new AddStockAlertResponseModel();

        //I need only the UserId coming from the BaseModel is binded from request headers
        var userId = requestModel.UserId;

        //I want all model data except UserId is binded with default model binding
        var stockInfo = requestModel.StockInfo;

        return response;
    }
}

到达 CustomerController 的每个请求在请求标头中都有一个“UserId”标头,我需要一个 ModelBinder 或 ParameterBinder 或一些仅绑定来自请求标头的 UserId 而不会触及其他模型参数的功能。我的意思是除了 UserId 之外的模型参数默认绑定..

我不想使用 AOP 或拦截器或方面。是否可以仅将 UserId 与模型绑定器、参数绑定器等 asp.net 功能绑定。

4

1 回答 1

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();
        }
    }
}
于 2014-01-02T16:42:31.603 回答