Web Api模型绑定和多态继承 [英] Web Api Model Binding and Polymorphic Inheritance

查看:168
本文介绍了Web Api模型绑定和多态继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在问是否有人知道是否有可能将继承自抽象类的具体类传递给Web Api.

I am asking if anyone knows if it is possible to to pass into a Web Api a concrete class that inherits from a abstract class.

例如:

public abstract class A{
    A();
}

public class B : A{

}

[POST("api/Request/{a}")]
public class Request(A a)
{
}

目前,我环顾四周,大多数解决方案似乎都表明使用TypeNameHandling可以正常工作.

At present I have looked around and most solutions seem to say that using TypeNameHandling will work.

JsonMediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
            jsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;

但是事实并非如此.另外,我的模型正在从控制台应用程序传递到webapi.我已经读到我可以反序列化json对象,并且尝试了几次之后,我认为这是行不通的.

However this is not that case. Also my model is being passed from a console app to the webapi. I have read that I may be able to deserialize the json object and after attempting this a few times I decide this was not going to work.

我已经考虑过创建一个客户模型联编程序,但是,我不想使我的应用程序变得比原来更复杂.目前,我从具有3个模型的抽象类继承,但将来可能会对此进行扩展.您可能会注意到,添加自定义模型联编程序可能需要多个联编程序,除非有一种方法可以使所有类型的抽象类通用一个联编程序.

I have looked into creating a customer model binder however, I do not want to make my application more complex that it has to be. At present I inherit from the abstract class with 3 models but may in the future extend this. As you may note adding custom model binders may require multiple binders unless there is a way of making one binder generic for all types of the abstract class.

要在我的控制台应用程序中对此进行扩展,我已经实例化了类b,然后在将其发布到我的webapi之前将其传递给ObjectContent

To expand on this in my console app I have instantiated class b as such and then passed it to the ObjectContent before posting to my webapi

item = B();

//serialize and post to web api
MediaTypeFormatter formatter;
JsonMediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
jsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;
formatter = jsonFormatter;

_content = new ObjectContent<A>(item, formatter);
var response = _client.PostAsync("api/Request", _content).Result;

调用webapi动作时,该对象为空

when the webapi action is called the object is null

推荐答案

可以通过默认模型绑定来实现.检查以下方法.

This is possible via the default model binding. check below method.

public abstract class RequestBase
{
    public int ID { get; set; }
}

public class MyRequest : RequestBase
{
    public string Name { get; set; }
}



[RoutePrefix("api/home")]
public class HomeController : ApiController
{
    [HttpPost]
    [Route("GetName")]
    public IHttpActionResult GetName([FromBody]MyRequest _request)
    {
        return Ok("Test");
    }
}

这篇关于Web Api模型绑定和多态继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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