网页API模型绑定和多态传承 [英] Web Api Model Binding and Polymorphic Inheritence

查看:183
本文介绍了网页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)
{
}

在present我环顾四周,大部分的解决方案似乎是说,使用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.

我看着但是创建一个客户模型绑定,我不想让我的应用程序更复杂,它必须是。在present我从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级这样,然后将其传递给ObjectContent张贴到我的WebAPI

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行动被称为对象为null

when the webapi action is called the object is null

推荐答案

由于LiamK指出,他的解决方案将无法在工作的WebAPI。的WebAPI使用 IModelBinder 接口绑定和 ModelMetadataProviders 将不会存在这些模型。

As LiamK has pointed out, his solution will not work in WebAPI. WebAPI uses the IModelBinder interface for binding and ModelMetadataProviders will not exist for those models.

我已经提供了此处此问题的解决方案;

I have provided a solution for this problem here;

<一个href=\"http://stackoverflow.com/questions/37282014/webapi-custom-model-binding-of-complex-abstract-object\">WebAPI定制型号复杂的抽象对象结合

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

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