ASP.NET WebAPI Supported Media Types per Method
Asked Answered
I

1

6

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

Iago answered 16/11, 2012 at 18:44 Comment(0)
S
5

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.

Stacy answered 16/11, 2012 at 19:24 Comment(1)
Link is dead, you can check the example in this link #51159471William

© 2022 - 2024 — McMap. All rights reserved.