模型绑定 – WebApi2:自定义参数绑定以绑定部分参数

我有一个webApi2项目和另一个项目,其中我有我的Model类和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或拦截器或方面..是否可以仅使用asp.net功能绑定UserId,如模型绑定器,参数绑定器等.

解决方法

以下是使用HttpParameterBinding的快速示例.在这里,我创建一个定义参数绑定,我让认的基于FromBody的绑定使用格式化程序来反序列化请求主体,然后从请求标头获取用户标识并在反序列化对象上设置. (您可能需要在以下代码添加其他验证检查).
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();
        }
    }
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....