繁体   English   中英

自定义HttpParameterBinding不被调用

[英]custom HttpParameterBinding not being called

通过将以下内容添加到Global.asax.cs,我向ASP.net MVC应用程序(版本5.2.0)添加了自定义参数绑定

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吗?

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

我希望我在这里不会缺少一些重要的东西,但是如果您有一个int类型的动作参数,如何将其分配给任何Deserialize返回的值(这是一个object )?

考虑从ParameterBindingAttribute派生。 这样,您可以将绑定逻辑应用于有意义的地方。

首先重写GetBinding方法:

public override HttpParameterBinding GetBinding(HttpParameterDescriptor httpParamDescriptor)

然后使用HttpParameterDescriptor来检查其类型是否有意义(在您的情况下,该类型应为“对象”)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM