[英]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.