问题
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