我有两个注册路线的区域,如下所示:
“网站”区域:
context.MapRoute(
"Landing Controllers",
"{controller}/{action}",
new { controller = "Home", action = "Index" }
);
“移动”区域:
context.MapRoute(
"Mobile Defaults",
"{controller}/{action}",
new { controller = "MobileHome", action = "Index" },
new { controller = "MobileHome", action = "Index" }
);
默认情况下,当尝试访问根 URL /
时,将始终采用其中一个或另一个路由。但假设我们使用自定义 AuthorizeAttribute
装饰我们的 Controller 操作,其中重写 OnAuthorization
方法以在适当时将用户重定向到正确的 Controller ,如下所示。 (想法取自伟大的blog post。)
public class MobileRedirectAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
var result = // Logic to generate the ActionResult that conditionally
// takes us to the other route goes here.
filterContext.Result = result;
}
}
我尝试使用新的 RedirectResult
和 RedirectToRouteResult
,但由于路由冲突,这两个方法都无法按我想要的方式工作。有没有办法将 AuthorizationContext.Result
设置为一个值,使我们能够执行当前未执行的操作? (作为最后的手段,我可以在移动路线上添加某种命名空间变量作为前缀,但我想避免走这条路。)
我的问题也可以通过查看维基百科的桌面/移动路由来总结。他们的两个网站,http://en.m.wikipedia.org/wiki/Main_Page和 http://en.wikipedia.org/wiki/Main_Page也共享相同的路线,但是,根据您所处的模式,返回非常不同的结果。
是否可以在 MVC 项目中设置维基百科的路由,其中每个环境(移动/桌面)都在其自己的区域中注册?
最佳答案
一位同事使用自定义 IRouteConstraint
引导我找到了一个很有前景的解决方案。
public class HelloWorldConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route,
string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
// Determine whether to accept the route for this request.
var browser = BrowserDetector.Parse(httpContext.Request.UserAgent);
if (browser == BrowserPlatform.Mobile)
{
return true;
}
return false;
}
}
我的路由声明现在如下所示,其中路由约束附加到随机选择的路由参数。
context.MapRouteLowercase(
"Mobile Defaults",
"{controller}/{action}",
new { controller = "MobileHome", action = "Index" },
// In this case, it's not so much necessary to attach the constraint to
// a particular route parameter as it is important to be able to inspect
// the HttpContextBase provided by the IRouteConstraint.
new {
controller = new HelloWorldConstraint()
}
);
关于c# - 两个区域是否可以共享同一条路线并且仍然可以到达?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21783986/