How can I extend content negotiation behavior in MVC4?

I am working on a RESTful API design, and I sent one of the questions that I have about content alignment to the Programmers StackExchange website here .

Based on this, I am interested in how I would support the following behavior in MVC4:

  • If the extension is specified in the URL (e.g. GET /api/search.json or /api/search.xml ), override the default content negotiation behavior in MVC4
  • If no extension is specified, use the default behavior to check the accept header value for application/xml or application.json .

What will be the cleanest / easiest way to capture this extension and change content negotiation behavior?

+4
source share
1 answer

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(); } 
+9
source

Source: https://habr.com/ru/post/1401377/


All Articles