在阅读了 MSDN https://msdn.microsoft.com/en-us/library/cc668201(v=vs.110).aspx上的文章后,我想出了以下解决方案:
- 实现一个自定义 MvcHandler 来处理选择控制器的逻辑
- 实现 IRouteHandler
- 将 IRouteHandler 附加到在 AreaRegistration 中注册的路由
public class MyRouteHandler : IRouteHandler
{
IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
{
return new MyMvcHandler(requestContext);
}
}
public class MyMvcHandler : MvcHandler, IHttpHandler
{
public MyMvcHandler(RequestContext requestContext) : base(requestContext)
{
}
private string GetControllerName(HttpContextBase httpContext)
{
string controllerName = this.RequestContext.RouteData.GetRequiredString("controller");
var groupId = httpContext.Session["GroupId"] as string;
if (!String.IsNullOrEmpty(groupId) && !String.IsNullOrEmpty(controllerName))
{
controllerName = groupId + controllerName;
}
return controllerName;
}
protected override IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)
{
RequestContext.RouteData.Values["controller"] = this.GetControllerName(httpContext);
return base.BeginProcessRequest(httpContext, callback, state);
}
}
最后,注册 RouteHandler:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"default",
"{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
).RouteHandler = new MyRouteHandler();
}