相关疑难解决方法(0)

将Json反序列化为Asp.Net Web API中的派生类型

我正在调用我的WebAPI的方法,发送一个我希望与模型匹配(或绑定)的json.

在控制器中我有一个方法,如:

public Result Post([ModelBinder(typeof(CustomModelBinder))]MyClass model);
Run Code Online (Sandbox Code Playgroud)

'MyClass',作为参数给出的是一个抽象类.我想这样,根据传递的json的类型,实例化正确的继承类.

为了实现它,我正在尝试实现自定义绑定器.问题是(我不知道它是否非常基本,但我找不到任何东西)我不知道如何检索请求中的原始Json(或更好的,某种序列化).

我知道了:

  • actionContext.Request.Content

但是所有方法都暴露为异步.我不知道这适合将生成模型传递给控制器​​方法...

非常感谢!

c# asp.net-mvc asp.net-web-api

59
推荐指数
2
解决办法
4万
查看次数

在Asp.Net Web API中实现自定义模型绑定器时出错

我坚持这个非常奇怪的问题.
我有一个名为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访问此控制器时.我得到一个错误说 …

c# custom-model-binder asp.net-mvc-4 asp.net-web-api

3
推荐指数
1
解决办法
4030
查看次数