MVC 3 use different controllers based on request parameters

ぐ巨炮叔叔 提交于 2019-12-19 04:59:06

问题


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 do.

I would like to use a path like:

/{projectId}

And have a place somewhere early on in the life-cycle where I have access to the route value dictionary that I can query a database or a session object to get the controller name to use for this request. Then be able to specify the controller to use route.Values["controller"] = controllerName; and have the request be made through that controller with all the jazz of request parameters and the like.

Is it possible?

I'm currently using areas, and have paths like:

/ProjectType1/{projectId}
/ProjectType2/{projectId}

but I'm finding it a real headache dealing with areas in all the Html.Link's and hate defining new areas for each project type. I would love to find something more dynamic.


回答1:


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


来源:https://stackoverflow.com/questions/7206065/mvc-3-use-different-controllers-based-on-request-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!