每个方法ASP.NET WebAPI支持的媒体类型 [英] ASP.NET WebAPI Supported Media Types per Method

查看:186
本文介绍了每个方法ASP.NET WebAPI支持的媒体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出控制器中的方法:

public class CustomerController : ApiController
{
    [HttpGet]
    public CustomerDto GetById([FromUri] int id)
    {
        .
        .
        return customerDto
    }
}

是否可以通过属性指定受支持的媒体类型?例如,CustomerDto是一个复杂的类,将仅使用JSON(应用程序/json)而不是XML(应用程序/xml)进行序列化,但也可以接受PDF(应用程序/pdf).是否有这样的东西:

Is there a way to specify supported Media Types with an attribute? For instance, CustomerDto is a complex class and will only serialize with JSON (application/json) not XML (application/xml) but could also accept PDF (application/pdf). Is there something like this:

[HttpGet(Accepts.JSON, Accepts.PDF)]  
    or
[HttpGet][AcceptJSON][AcceptXML]
    or
[HttpGet][Accept("application/json")][Accept("application/pdf")]

如果不支持传入请求,则可能返回不支持的异常/状态.

If the incoming request wasn't supported a Unsupported Exception / Status could be returned.

注意-我不想像全局性那样一起删除XML序列化.相反,我想定义每条路线接受什么.

Note - I don't want to remove say XML serialization all together as could be done globally. Instead, I would like to define what is accepted per route.

使用-ASP.NET WebAPI RC 1(需要升级)+自托管

Using - ASP.NET WebAPI RC 1 (need to upgrade) + Self Hosting

推荐答案

类似自定义ActionFilterAttribute的声音可能会解决问题.

Sounds like a custom ActionFilterAttribute might do the trick.

创建一个继承自System.Web.Http.Filters.ActionFilterAttribute的新类,重写OnActionExecuting方法.在此方法内,您可以检查请求的标头,查找您不希望支持的内容并返回适当的响应.

Create a new class that inherits from System.Web.Http.Filters.ActionFilterAttribute, override the OnActionExecuting method. Inside this method, you could check the request's headers, look for what you don't want to support and return an appropriate response.

自定义ActionFilterAttribute的构造函数可以包含要处理的哪些接受"类型以及要拒绝的哪些接受"类型的详细信息.

The constructor for your custom ActionFilterAttribute could take the details of which "accept" types you want to process and which ones you want to reject.

有关自定义ActionFilterAttribute的示例,请查看这篇文章.

For an example of a custom ActionFilterAttribute, check out this post.

这篇关于每个方法ASP.NET WebAPI支持的媒体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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