I am working on a Web API and I want to use Content Negotiation with file extensions to allow browser clients to specify the content they want to receive. For instance
http://localhost:54147/data.xslx.
According to this article (http://msdn.microsoft.com/en-us/magazine/dn574797.aspx) I should be able to setup routing with something like this
//setup default routes
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "{controller}/{id}",
defaults: new {id = RouteParameter.Optional}
);
//setup routes with extensions config.Routes.MapHttpRoute( name: "Url extension", routeTemplate: "{controller}/{action}.{ext}/{id}", defaults: new { id = RouteParameter.Optional } );
Here is my simple controller
public class TestController : ApiController
{
public HttpResponseMessage Get()
{
var items = new[] {"test1", "test2", "test3"};
return Request.CreateResponse(HttpStatusCode.OK, items);
}
}
using this url
http://localhost:54147/test/get.xlsx
I always get the browser default (xml in chrome, json in IE11).
or possibly
http://localhost:54147/test.xlsx
to which I get the error
No HTTP resource was found that matches the request URI 'http://localhost:54147/test.xlsx'.
I should be able to use my custom formatter. But it's not happening. Here is the constructor of my custom formatter.
public ExcelFormatter()
{
MediaTypeMappings.Add(new UriPathExtensionMapping("xlsx", ContentType.Excel));
SupportedMediaTypes.Add(new MediaTypeHeaderValue(ContentType.Excel));
}
Again according to the article this should help the API Content Negotiator use my custom formatter. I appreciate any help.
As the question is old, but is still without an answer:
Generally this links should help:
How to build media formatter
Microsofts words about content negotiation
To the code in the question:
BufferedMediaTypeFormatter
(sync) or MediaTypeFormatter`(async)HttpConfiguration.Formatters
(link)You probably want to do this in an config for the complete application. For testing you could add in to a single ApiController like following.
untested example