简体   繁体   中英

custom HttpParameterBinding not being called

I added a custom parameter binding to my ASP.net MVC app (version 5.2.0), by adding the following to Global.asax.cs

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

The definition of NewtonsoftParameterBinding is

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

So I was hoping this would allow me to use things like JsonProperty on my MVC model fields, but it's never called. Does anyone know how I can correctly register a custom ParameterBindingRules ?

Adding the HttpParameterBinding to ParameterBindingRules globally will attempt to bind all the parameters in all the actions in this way. Are all your params of type object?

I hope I'm not missing something major here but if you have an action parameter of type int how can you assign it to whatever Deserialize returns (which is an object )?

Consider deriving from ParameterBindingAttribute . This way you can apply your binding logic to where it make sense.

Start by overriding the GetBinding method:

public override HttpParameterBinding GetBinding(HttpParameterDescriptor httpParamDescriptor)

Then use the HttpParameterDescriptor to check if its type makes sense (in your case it should be of '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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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