Asp.net mvc 4 如何在Asp Net MVC 4 Web Api中访问自定义模型绑定器中的请求内容?
我一直在思考如何解决我在上一个问题中遇到的问题 我很高兴我可以使用自己的自定义模型绑定器,这样我就可以处理完美的情况,当我得到我不期望的数据时,我可以将其写入日志 我有下面的类和模型活页夹Asp.net mvc 4 如何在Asp Net MVC 4 Web Api中访问自定义模型绑定器中的请求内容?,asp.net-mvc-4,asp.net-web-api,custom-model-binder,Asp.net Mvc 4,Asp.net Web Api,Custom Model Binder,我一直在思考如何解决我在上一个问题中遇到的问题 我很高兴我可以使用自己的自定义模型绑定器,这样我就可以处理完美的情况,当我得到我不期望的数据时,我可以将其写入日志 我有下面的类和模型活页夹 public class Person { public int Id { get; set; } public string Name { get; set; } } public class CustomPersonModelBinder : IModelBinder { p
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class CustomPersonModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var myPerson = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var myPersonName = bindingContext.ValueProvider.GetValue("Name");
var myId = bindingContext.ValueProvider.GetValue("Id");
bindingContext.Model = new Person {Id = 2, Name = "dave"};
return true;
}
}
public class CustomPersonModelBinderProvider : ModelBinderProvider
{
private CustomPersonModelBinder _customPersonModelBinder = new CustomPersonModelBinder();
public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
{
if (modelType == typeof (Person))
{
return _customPersonModelBinder;
}
return null;
}
}
这是我的控制器方法
public HttpResponseMessage Post([ModelBinder(typeof(CustomPersonModelBinderProvider))]Person person)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
我一直在用fiddler和
Post http://localhost:18475/00.00.001/trial/343
{
"Id": 31,
"Name": "Camera Broken"
}
这非常有效,在不使用自定义模型绑定器的情况下,我可以在post方法中从json数据中获得Person对象,而使用自定义模型绑定器,我始终可以获得Person(Id=2,Name=“dave”)
问题是我似乎无法访问自定义模型绑定器中的JSon数据
bindModel方法中的myPerson和myPersonName变量均为null。但是,myId变量中填充了343
你知道如何在BindModel方法中访问json中的数据吗?试试这个:
actionContext.Request.Content.ReadAsStreamAsync()
我不明白你为什么需要为
人
定制模型活页夹。默认的模型绑定器可以很好地处理有效的JSON。你到底有什么问题?