WebApi2:自定义参数绑定以绑定部分参数 [英] WebApi2: Custom parameter binding to bind partial parameters

查看:328
本文介绍了WebApi2:自定义参数绑定以绑定部分参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 BaseModel
{
    public string UserId { get; set; }
}

所有其他模型均来自我的BaseModel.

All the other models are derived from my BaseModel.

在webapi中,我的CustomerController如下,

In webapi I have my CustomerController as following,

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之外的模型参数都将被绑定..

Every request that comes to CustomerController has a "UserId" header in request headers and I need a ModelBinder or ParameterBinder or some functionality that binds only the UserId from request headers without touching the other model parameters. I mean model parameters except UserId are to be binded by default..

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

I don't want to use AOP or interceptors or aspects.. Is it possible to bind only UserId with an asp.net functionality like model binders, parameter binders, etc.

推荐答案

以下是使用HttpParameterBinding的快速示例.在这里,我正在创建一个自定义参数绑定,在该绑定中,我让基于默认FromBody的绑定使用格式器对请求正文进行反序列化,然后从请求标头中获取用户ID并在反序列化对象上进行设置. (您可能需要在以下代码上添加其他验证检查).

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

这篇关于WebApi2:自定义参数绑定以绑定部分参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆