MVC 3 use different controllers based on request parameters

前端 未结 1 1763
执笔经年
执笔经年 2021-01-07 11:55

I\'ve been scouring the web for a solution for this the past couple days and I\'m not finding much. Hopefully I\'m not using the right terminology and it\'s an easy thing to

相关标签:
1条回答
  • 2021-01-07 12:27

    You could write a custom route:

    public class MyRoute : Route
    {
        public MyRoute(string url, IRouteHandler routeHandler)
            : base(url, routeHandler)
        { }
    
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            var rd = base.GetRouteData(httpContext);
            var projectId = rd.GetRequiredString("projectId");
    
            // TODO: Given the projectId decide which controller to choose:
            // you could query the database or whatever it is needed here
    
            if (projectId == "1")
            {
                rd.Values["controller"] = "Foo";
            }
            else if (id == "2")
            {
                rd.Values["controller"] = "Bar";
            }
            else if (id == "3")
            {
                rd.Values["controller"] = "Baz";
            }
            else
            {
                // unknown project id
                throw new HttpException(404, "Not found");
            }
    
            // we will always be using the Index action but this could
            // also be variable based on the projectId
            rd.Values["action"] = "index";
    
            return rd;
        }
    }
    

    and then register it:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.Add(new MyRoute("{projectId}", new MvcRouteHandler()));
    }
    

    Now:

    • /1 will invoke FooController/Index
    • /2 will invoke BarController/Index
    • /3 will invoke BazController/Index
    • /something_else will throw 404 Not found
    0 讨论(0)
提交回复
热议问题