问题
I have an application that is going to act as a "catch-all" for requests that could be coming from a variety of targets. I would like to be able to redirect to a different controller/action in my application based on the value of the "accept" header.
Clarification: I would like to do this without an HTTP Handler, if possible.
回答1:
You could write a custom 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 POST to /home and set the Accept request header to xml the Xml action of the Home controller will be hit.
回答2:
make a route.. just a simple class and derive it from RouteBase here you will find the method GetRouteData(System.Web.HttpContextBase httpContext) with return type of RouteData
u can pick out the headers of your choice from the httpcontext and add the values of ur route to the return value of the function..
回答3:
you can use Phil haack Route Magic plugin it has HttpHandler Routing but it use HttpHandler you can take a look , see if you like it
Route Magic
来源:https://stackoverflow.com/questions/10096605/with-mvc3-how-can-i-change-the-controller-action-based-on-the-accept-header