Web API 2.2 Content Negotiation with file extensions

359 views Asked by At

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.

1

There are 1 answers

0
MarkusH On

As the question is old, but is still without an answer:

Generally this links should help:


To the code in the question:

  • it seems you need to extend from BufferedMediaTypeFormatter(sync) or MediaTypeFormatter`(async)
  • you need to make your formatter known to 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

public class TestController : ApiController
{
    TestController() {
      Configuration.Formatters.Add(new ExcelFormatter());
    }

    public HttpResponseMessage Get()
    {
        var items = new[] {"test1", "test2", "test3"};
        return Request.CreateResponse(HttpStatusCode.OK, items);
    }
}
```