UriPathExtensionMapping to control response format in WebAPI
I am having a problem running UriPathExtensionMapping in ASP.NET WebAPI. My setup is like this:
My routes:
config.Routes.MapHttpRoute(
name: "Api UriPathExtension",
routeTemplate: "api/{controller}.{extension}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "Api UriPathExtension ID",
routeTemplate: "api/{controller}/{id}.{extension}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
My global ASAX file:
AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles);
My controller:
public IEnumerable<string> Get()
{
return new string[] { "Box", "Rectangle" };
}
// GET /api/values/5
public string Get(int id)
{
return "Box";
}
// POST /api/values
public void Post(string value)
{
}
// PUT /api/values/5
public void Put(int id, string value)
{
}
// DELETE /api/values/5
public void Delete(int id)
{
}
When making requests using curl, JSON is the default response, even when I explicitly request XML, I still get JSON:
curl http://localhost/eco/api/products/5.xml
Return:
"http://www.google.com"
Can anyone see the problem with my setup?
The following code displays the extensions in the Global.asax file after the routes have been configured:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.
MediaTypeMappings.Add(
new UriPathExtensionMapping(
"json", "application/json"
)
);
GlobalConfiguration.Configuration.Formatters.XmlFormatter.
MediaTypeMappings.Add(
new UriPathExtensionMapping(
"xml", "application/xml"
)
);
You need to register the extension mapping like so:
config.Formatters.JsonFormatter.MediaTypeMappings.Add(new UriPathExtensionMapping("json", "application/json"));
config.Formatters.XmlFormatter.MediaTypeMappings.Add(new UriPathExtensionMapping("xml", "application/xml"));
An example was found here .
Update
If you look at the code UriPathExtensionMapping
, the placeholder for the extension would be
/// <summary>
/// The <see cref="T:System.Uri"/> path extension key.
/// </summary>
public static readonly string UriPathExtensionKey = "ext";
So your routes should be changed to ({ext} not {extension}):
config.Routes.MapHttpRoute(
name: "Api UriPathExtension",
routeTemplate: "api/{controller}.{ext}/{id}",
defaults: new { id = RouteParameter.Optional }
);
As a complement to this answer, because I cannot comment yet, you should also make sure your web.config contains the line
<modules runAllManagedModulesForAllRequests="true" />
inside the section <system.webServer>
.
Mine didn't do it and this example didn't work for me until I added this line.