Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET WebAPI Supported Media Types per Method

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

like image 369
Mike Rowley Avatar asked Nov 16 '12 18:11

Mike Rowley


People also ask

What are the default media types supported by Web API?

Web API has built-in support for XML, JSON, BSON, and form-urlencoded data, and you can support additional media types by writing a media formatter.

Can Web API support vendor specific media types?

an API can (and often should, IMO) expose its resources using specialized media types. These often take the form of vendor-specific media types, such as application/vnd.

Which types of routing is supported in Web API?

Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources.

Which of the following Formatters is not supported by ASP NET core Web API?

The framework provides built-in input and output formatters for JSON and XML. It provides a built-in output formatter for plain text, but doesn't provide an input formatter for plain text.


1 Answers

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.

like image 125
Mark Berryman Avatar answered Sep 19 '22 14:09

Mark Berryman