MVC 3 根据请求参数使用不同的控制器 [英] MVC 3 use different controllers based on request parameters
问题描述
过去几天我一直在网上寻找解决方案,但我没有找到太多.希望我没有使用正确的术语,这很容易做到.
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.
我想使用如下路径:
/{projectId}
在生命周期的早期有一个地方,我可以访问路由值字典,我可以查询数据库或会话对象以获取用于此请求的控制器名称.然后能够指定控制器使用 route.Values["controller"] = controllerName;
并通过该控制器发出请求,并使用所有爵士乐请求参数等.
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.
有可能吗?
我目前正在使用区域,并且有如下路径:
I'm currently using areas, and have paths like:
/ProjectType1/{projectId}
/ProjectType2/{projectId}
但我发现处理所有 Html.Link
中的区域真的很头疼,并且讨厌为每个项目类型定义新区域.我很想找到更有活力的东西.
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.
推荐答案
您可以编写自定义路由:
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;
}
}
然后注册:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new MyRoute("{projectId}", new MvcRouteHandler()));
}
现在:
/1
将调用FooController/Index
/2
将调用BarController/Index
/3
将调用BazController/Index
/something_else
会抛出 404 Not found
/1
will invokeFooController/Index
/2
will invokeBarController/Index
/3
will invokeBazController/Index
/something_else
will throw 404 Not found
这篇关于MVC 3 根据请求参数使用不同的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!