绑定WebAPI中的抽象操作参数 [英] Binding abstract action parameters in WebAPI

查看:97
本文介绍了绑定WebAPI中的抽象操作参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我处于一种情况,我需要将传入的HTTP POST请求与主体中的数据绑定为具体类型,具体取决于数据中的ProductType分母.这是我的Web API 2操作方法:

I'm in a situation where I need to bind an incoming HTTP POST request with data in the body, to a concrete type depending on a ProductType denominator in the data. Here is my Web API 2 action method:

[HttpPost, Route]
public HttpResponseMessage New(ProductBase product)
{
    // Access concrete product class...

    if (product is ConcreteProduct)
        // Do something
    else if (product is OtherConcreteProduct)
        // Do something else
}

我最初是想使用自定义模型绑定程序,但是它

I was first thinking of using a custom model binder, but it seems like it isn't possible to access the request body at that point:

对于复杂类型,Web API尝试从消息中读取值 正文,使用媒体类型的格式化程序.

For complex types, Web API tries to read the value from the message body, using a media-type formatter.

我真的看不到媒体类型格式化程序如何解决此问题,但我可能缺少一些东西.您将如何解决这个问题?

I can't really see how media-type formatters solves this problem, but I'm probably missing something. How would you solve this problem?

推荐答案

根据请求的内容类型,您将不得不确定要实例化的具体类.让我们以application/json为例.对于这种现成的内容类型,Web API使用JSON.NET框架将请求主体有效负载反序列化为一个具体对象.

Depending on the request content type you will have to decide which concrete class to instantiate. Let's take an example with application/json. For this content type out-of-the-box the Web API is using the JSON.NET framework to deserialize the request body payload into a concrete object.

因此,您必须加入此框架才能实现所需的功能.此框架中的一个很好的扩展点是编写自定义JsonConverter.假设您具有以下类:

So you will have to hook into this framework in order to achieve the desired functionality. A good extension point in this framework is writing a custom JsonConverter. Let's suppose that you have the following classes:

public abstract class ProductBase
{
    public string ProductType { get; set; }
}

public class ConcreteProduct1 : ProductBase
{
    public string Foo { get; set; }
}

public class ConcreteProduct2 : ProductBase
{
    public string Bar { get; set; }
}

和以下操作:

public HttpResponseMessage Post(ProductBase product)
{
    return Request.CreateResponse(HttpStatusCode.OK, product);
}

让我们编写一个自定义转换器来处理这种类型:

Let's write a custom converter to handle this type:

public class PolymorphicProductConverter: JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(ProductBase);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var obj = JObject.Load(reader);
        ProductBase product;
        var pt = obj["productType"];
        if (pt == null)
        {
            throw new ArgumentException("Missing productType", "productType");
        }

        string productType = pt.Value<string>();
        if (productType == "concrete1")
        {
            product = new ConcreteProduct1();
        }
        else if (productType == "concrete2")
        {
            product = new ConcreteProduct2();
        }
        else
        {
            throw new NotSupportedException("Unknown product type: " + productType);
        }

        serializer.Populate(obj.CreateReader(), product);
        return product;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

,最后一步是在WebApiConfig中注册此自定义转换器:

and the last step is to register this custom converter in the WebApiConfig:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
    new PolymorphicProductConverter()
);

就足够了.现在,您可以发送以下请求:

And that's pretty much it. Now you can send the following request:

POST /api/products HTTP/1.1
Content-Type: application/json
Host: localhost:8816
Content-Length: 39

{"productType":"concrete2","bar":"baz"}

,服务器将正确反序列化此消息并响应:

and the server will properly deserialize this message and respond with:

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
Date: Sat, 25 Jan 2014 12:39:21 GMT
Content-Length: 39

{"Bar":"baz","ProductType":"concrete2"}

如果您需要处理其他格式,例如application/xml,则可以执行相同的操作,然后插入相应的序列化器.

If you need to handle other formats such as application/xml you might do the same and plug into the corresponding serializer.

这篇关于绑定WebAPI中的抽象操作参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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