With MVC3, how can I change the controller / action based on the accept header?

I have an application that will act as a "trick" for requests that may arise from different purposes. I would like to be able to redirect to another controller / action in my application based on the value of the "accept" header.

Explanation: I would like to do this without an HTTP handler, if possible.

+1
source share
3 answers

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.

+4
source

make a route .. just a simple class and get it out of RouteBase here you will find the GetRouteData(System.Web.HttpContextBase httpContext) method GetRouteData(System.Web.HttpContextBase httpContext) with the return type RouteData u can select the headers of your choice from httpcontext and add the values โ€‹โ€‹of the ur route to the return value of the function.

0
source

you can use the fix-how Route Magic plugin HttpHandler Routing but it uses HttpHandler, you can take a look, see if you like it

Route magic

0
source

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


All Articles