我正在调用我的WebAPI的方法,发送一个我希望与模型匹配(或绑定)的json.
在控制器中我有一个方法,如:
public Result Post([ModelBinder(typeof(CustomModelBinder))]MyClass model);
Run Code Online (Sandbox Code Playgroud)
'MyClass',作为参数给出的是一个抽象类.我想这样,根据传递的json的类型,实例化正确的继承类.
为了实现它,我正在尝试实现自定义绑定器.问题是(我不知道它是否非常基本,但我找不到任何东西)我不知道如何检索请求中的原始Json(或更好的,某种序列化).
我知道了:
但是所有方法都暴露为异步.我不知道这适合将生成模型传递给控制器方法...
非常感谢!
我坚持这个非常奇怪的问题.
我有一个名为AttendanceControllerderived 的API控制器APIControllerFA,从ApiController
这里派生出来的是代码
public class AttendanceController : ApiControllerFA
{
public HttpResponseMessage PostAttendance([ModelBinder(typeof(AttendanceRegistrationModelBinder))]AttendanceRegistrationModel model)
{
//checking model state for errors
//throw new Exception("Just to throw an error ");
...........
Run Code Online (Sandbox Code Playgroud)
从PostAttendance方法可以看出,我有一个自定义ModelBinder命名AttendenceRegistrationModelBinder,这是代码
public class AttendanceRegistrationModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name == "formJson")
{
string val = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name).AttemptedValue;
dynamic jsonVal = JsonConvert.DeserializeObject(val);
propertyDescriptor.SetValue(bindingContext.Model, jsonVal);
return;
//SetProperty(controllerContext, bindingContext,propertyDescriptor,jsonVal);
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用Fiddler访问此控制器时.我得到一个错误说 …