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、インターセプター、またはアスペクトを使用したくありません。モデル バインダー、パラメーター バインダーなどの asp.net 機能で UserId のみをバインドすることは可能ですか?

4

1 に答える 1

11

以下は、 を使用した簡単な例HttpParameterBindingです。ここでは、デフォルトFromBodyベースのバインディングでフォーマッタを使用してリクエスト ボディをデシリアライズし、リクエスト ヘッダーからユーザー 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();
        }
    }
}
于 2014-01-02T16:42:31.603 に答える