我可以在一个界面基于对象传递给一个MVC 4的WebAPI POST? [英] Can I pass an interface based object to an MVC 4 WebApi POST?

查看:133
本文介绍了我可以在一个界面基于对象传递给一个MVC 4的WebAPI POST?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个API这样:

I want to have an API as such:

public class RelayController : ApiController
{
    // POST api/values
    public void Post([FromBody]IDataRelayPackage package)
    {
        MessageQueue queue = new MessageQueue(".\\private$\\DataRelay");
        queue.Send(package);
        queue.Close();
    }
}

我得到了一揽子空值,所以我想知道什么可能会出错。我唯一​​的想法是,默认的 JSON 串行器无法处理这个问题,但我不清楚如何解决它。

I'm getting a null value for 'package' so I'm wondering what might be going wrong. My only thoughts are that the default JSON serializer can't handle this, but I'm unclear how to fix it.

推荐答案

您可以用自定义模型绑定做到这一点很容易。下面是我工作。 (使用Web API 2和6 JSON.Net)

You can do this fairly easily with a custom model binder. Here is what worked for me. (Using Web API 2 and JSON.Net 6)

public class JsonPolyModelBinder : IModelBinder
{
    readonly JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto };

    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var content = actionContext.Request.Content;
        string json = content.ReadAsStringAsync().Result;
        var obj = JsonConvert.DeserializeObject(json, bindingContext.ModelType, settings);
        bindingContext.Model = obj;
        return true;
    }
}

在Web API控制器看起来是这样的。 (注:也应定期MVC行动的工作 - 我做了这样的事情他们以前也是)

The Web API controller looks like this. (Note: should also work for regular MVC actions -- I've done something like this for them before as well.)

public class TestController : ApiController
{
    // POST api/test
    public void Post([ModelBinder(typeof(JsonPolyModelBinder))]ICommand command)
    {
        ...
    }
}

我也应该注意到,当你序列化JSON,你应该使用相同的设置序列化,序列化和作为一个接口,使自动踢,包括类型提示。事情是这样的。

I should also note that when you serialize the JSON, you should serialize it with the same setting, and serialize it as an interface to make the Auto kick in and include the type hint. Something like this.

    JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto };
    string json = JsonConvert.SerializeObject(command, typeof(ICommand), settings);

这篇关于我可以在一个界面基于对象传递给一个MVC 4的WebAPI POST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆