【问题标题】:WebAPI Actions with multiple complex types, one of which is injected with a filter具有多种复杂类型的 WebAPI Actions,其中一种注入了过滤器
【发布时间】:2014-01-17 16:40:00
【问题描述】:

我有一个 WebAPI 方法如下:

public HttpResponseMessage Post(ITradeCustomerPrincipal user, OrderModel value)

我得到了错误

无法将多个参数(“用户”和“值”)绑定到请求的内容。

当我尝试调用它时。我明白为什么。

我有一个全局应用的属性,它将ITradeCustomerPrincipal 注入到任何操作中,如下所示:

public class TradeConsumerFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var matchedArguments = actionContext.ActionDescriptor.ActionBinding.ParameterBindings
                                            .SingleOrDefault(pb => typeof(ITradeCustomerPrincipal).IsAssignableFrom(pb.Descriptor.ParameterType));

        if (matchedArguments != null)
        {
            var TradeCustomerPrincipal = HttpContext.Current.User as ITradeCustomerPrincipal;

            if (TradeCustomerPrincipal != null)
            {
                actionContext.ActionArguments[matchedArguments.Descriptor.ParameterName] = TradeCustomerPrincipal;
            }
        }

        base.OnActionExecuting(actionContext);
    }
}

这样action就不需要自己绑定ITradeCustomerPrincipal了,由属性自动完成。

我如何告诉操作不要绑定正文(或我猜的任何地方)的 user 参数,因为它是由操作过滤器预先设置的?

【问题讨论】:

    标签: c# asp.net-web-api


    【解决方案1】:

    我已经设法通过创建一个什么都不做的模型绑定器并将其应用于user 参数来实现这一点,它工作正常,因为它不是分配/创建对象的绑定器。

    模型绑定器:

    public class NoOpModelBinder : IModelBinder
    {
        public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            return true;
        }
    }
    

    新的动作方法签名:

    public HttpResponseMessage Post([ModelBinder(typeof(NoOpModelBinder))] ITradeCustomerPrincipal user, OrderModel value)
    

    我已经设法弄清楚如何将模型绑定器全局应用于接口(您不能将属性应用于接口,只能应用于类):

    GlobalConfiguration.Configuration.BindParameter(typeof(ITradeCustomerPrincipal), new NoOpModelBinder());
    

    这意味着任何带有此参数的动作签名都可以在没有ModelBinder 属性的情况下工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-14
      • 2021-02-24
      • 2011-08-05
      • 1970-01-01
      • 2017-11-03
      • 2020-06-24
      • 2015-09-28
      • 2018-01-17
      相关资源
      最近更新 更多