kimsagro
kimsagro

Reputation: 17425

WebApi - Specify Content-Type in Uri

You can use

AddUriPathExtensionMapping("json", "application/json");

To enable media type to be specified as part of the uri as seen below

http://localhost/products.json

How can I get WebApi to allow me to post to this uri without having to specify a Content-Type header. I would like WebApi to use the extension to determine the Content-Type.

Upvotes: 1

Views: 2241

Answers (2)

Darrel Miller
Darrel Miller

Reputation: 142222

You could add a server side message handler that parses the URI and sets the Content-Type header before it reaches the ApiController.

Upvotes: 0

Kiran
Kiran

Reputation: 57989

Question: Why would you want to specify the Content-Type in the Uri? Usually specifying the media type in the Uri is for GET kind of scenarios and where the user does not have a way to provide the Accept header. For example, in the browser address bar, one could enter /products.json or /products.xml to see the results.

For all other scenarios where you can make a request with headers, you should be sending them in regular way. Could you describe your scenario more?

Edited:

If you indeed are looking for GET requests, then you could do like in the following example:

  • Register routes like below:

        config.Routes.MapHttpRoute(
                name: "DefaultApiWithExtension2",
                routeTemplate: "api/{controller}/{id}.{ext}"
            );
    
        config.Routes.MapHttpRoute(
            name: "DefaultApiWithExtension1",
            routeTemplate: "api/{controller}.{ext}");
    
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    
        config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "application/xml");
        config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
    
  • If your application is hosted in IIS, then you would see errors in using the . character in the url. You can resolve this by having the following setting in Web.Config:
    <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />

Upvotes: 2

Related Questions