You can use UriPathExtensionMapping in formatters for this. These mappings allow you to “assign” an extension for formatting so that they take precedence during content negotiation. You also need to add a route so that queries with the extension are also requested. The code below shows the changes required by the default template to enable this scenario.
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapHttpRoute( name: "Api with extension", routeTemplate: "api/{controller}.{ext}/{id}", defaults: new { id = RouteParameter.Optional, ext = RouteParameter.Optional } ); routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); GlobalConfiguration.Configuration.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml"); GlobalConfiguration.Configuration.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json"); BundleTable.Bundles.RegisterTemplateBundles(); }
source share