我一直在思考如何解决我在上一个问题中遇到的问题
我可以访问 .net Web api 模型绑定无法处理的数据吗?
我可以使用我自己的自定义模型绑定器,这样我就可以处理完美的案例,并在我得到我不期望的数据时写入日志。
我有以下课程和模型绑定器
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);
}
我一直在使用提琴手来调用它
Post http://localhost:18475/00.00.001/trial/343
{
"Id": 31,
"Name": "Camera Broken"
}
这很好用,在不使用自定义模型绑定器的情况下,我在 post 方法中从我的 json 数据中填充了一个 Person 对象,并且使用自定义模型绑定器,我总是得到一个人(Id= 2,Name =“dave”)。
问题是我似乎无法访问自定义模型活页夹中的 JSon 数据。
bindModel 方法中的 myPerson 和 myPersonName 变量都是 null。但是 myId 变量填充了 343。
任何想法如何在我的 BindModel 方法中访问 json 中的数据?