gpt4 book ai didi

model-binding - WebApi2 : Custom parameter binding to bind partial parameters

转载 作者:行者123 更新时间:2023-12-04 07:29:24 25 4
gpt4 key购买 nike

我有一个 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 的每个请求在请求 header 中都有一个“UserId” header ,我需要一个 ModelBinder 或 ParameterBinder 或一些仅绑定(bind)来自请求 header 的 UserId 而不会触及其他模型参数的功能。我的意思是除了 UserId 之外的模型参数默认绑定(bind)..

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

最佳答案

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

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

关于model-binding - WebApi2 : Custom parameter binding to bind partial parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20855185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com