ASP.NET WebAPI Supported Media Types per Method

可紊 提交于 2020-01-13 10:21:49

问题


Given a method in a controller:

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

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.

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.

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


回答1:


Sounds like a custom ActionFilterAttribute might do the trick.

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.

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.

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



来源:https://stackoverflow.com/questions/13422524/asp-net-webapi-supported-media-types-per-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!