You can write your own route:
public class MyRoute : Route { public MyRoute(string url, object defaults) : base(url, new RouteValueDictionary(defaults), new MvcRouteHandler()) { } public override RouteData GetRouteData(HttpContextBase httpContext) { var rd = base.GetRouteData(httpContext); if (rd == null) { return null; } var accept = httpContext.Request.Headers["Accept"]; if (string.Equals("xml", accept, StringComparison.OrdinalIgnoreCase)) { rd.Values["action"] = "xml"; } else if (string.Equals("json", accept, StringComparison.OrdinalIgnoreCase)) { rd.Values["action"] = "json"; } return rd; } }
and then register this route:
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.Add( "Default", new MyRoute( "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ) ); }
Now when you send POST to /home
and set the Accept
request header to xml
, the xml
action of the Home
controller will be removed.
source share