我一直在思考如何解决我在上一个问题中遇到的问题
Can I get access to the data that the .net web api model binding was not able to handle?
我认为我可以使用自己的自定义模型绑定(bind)器,这样我就可以处理完美的情况,并在收到我不期望的数据时写入日志。
我有以下类和模型绑定(bind)器
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;
}
}
这是我的 Controller 方法
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"
}
这效果很好,在不使用自定义模型绑定(bind)程序的情况下,我在 post 方法中得到了一个由 json 数据填充的 Person 对象,并且使用自定义模型绑定(bind)程序我总是得到一个人(Id = 2,Name =“dave”) 。
问题是我似乎无法访问自定义模型绑定(bind)器中的 JSon 数据。
bindModel 方法中的 myPerson 和 myPersonName 变量均为 null。但是 myId 变量填充为 343。
有什么想法可以在 BindModel 方法中访问 json 中的数据吗?
最佳答案
试试这个:
actionContext.Request.Content.ReadAsStreamAsync()
关于asp.net-mvc-4 - 如何访问 Asp Net MVC 4 Web Api 中自定义模型绑定(bind)器中的请求内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13078732/