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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With