我可以将基于接口的对象传递给MVC 4 WebApi POST吗?

Dav*_*son 17 c# asp.net-mvc post interface asp.net-web-api

我希望有这样的API:

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

我得到'包'的空值,所以我想知道可能出错的地方.我唯一的想法是默认的JSON序列化程序无法处理这个,但我不清楚如何解决它.

Kas*_*man 17

您可以使用自定义模型绑定器轻松完成此操作.这对我有用.(使用Web API 2和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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Web API控制器看起来像这样.(注意:也应该适用于常规的MVC操作 - 我之前也为他们做了类似的事情.)

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

我还应该注意,当您序列化JSON时,您应该使用相同的设置对其进行序列化,并将其序列化为接口以使Auto启动并包含类型提示.像这样的东西.

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


Mar*_*nes 5

您正在尝试反序列化到接口.除非被告知,否则序列化程序将不知道要实例化的类型.

查看TypeNameHandling选项发布子类集合

或者看看创建自定义JsonConverter.看看这个问题如何在JSON.NET中实现自定义JsonConverter来反序列化基类对象的列表?