自定义HttpParameterBinding未被调用

时间:2014-08-05 16:03:23

标签: c# asp.net-mvc asp.net-mvc-5

我添加了一个自定义参数绑定到我的ASP.net MVC应用程序(版本5.2.0),方法是将以下内容添加到Global.asax.cs

GlobalConfiguration.Configuration.ParameterBindingRules.Insert(0, desc => new NewtonsoftParameterBinding(desc));

NewtonsoftParameterBinding的定义是

public class NewtonsoftParameterBinding : HttpParameterBinding
{
    private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings();

    public NewtonsoftParameterBinding(HttpParameterDescriptor descriptor) : base(descriptor) {}

    public override bool WillReadBody
    {
        get { return true; }
    }


    public override async Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext,
        CancellationToken cancellationToken)
    {
        var theString = await actionContext.Request.Content.ReadAsStringAsync();

        actionContext.ActionArguments[Descriptor.ParameterName] = JsonConvert.DeserializeObject(theString, Descriptor.ParameterType, _serializerSettings);
    }
}

所以我希望这会允许我在我的MVC模型字段中使用JsonProperty之类的东西,但它从未被调用过。有谁知道如何正确注册自定义ParameterBindingRules

1 个答案:

答案 0 :(得分:0)

全局地将HttpParameterBinding添加到ParameterBindingRules将尝试以这种方式绑定所有操作中的所有参数。你的所有类型对象都是对象吗?

我希望我不会错过这里的主要内容,但是如果你有一个int类型的动作参数,你如何将它分配给任何反序列化返回(object)?

考虑从ParameterBindingAttribute派生。这样,您就可以将绑定逻辑应用到合理的位置。

首先覆盖GetBinding方法:

public override HttpParameterBinding GetBinding(HttpParameterDescriptor httpParamDescriptor)

然后使用HttpParameterDescriptor检查它的类型是否有意义(在你的情况下它应该是'object')。

if(httpParamDescriptor.ParameterType == typeof(object))
{
    return new NewtonSoftParameterBinding(); 
}
else
{
    //indicate that this binding doesn't work for non-object types as follows
    return httpParamDescriptor.BindAsError("works with params of object type only");
}