两个区域是否可以共享相同的路由并且仍然可以访问?

时间:2014-02-14 16:05:37

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing

我有两个注册路线的区域,如下所示:

“网站”区域:

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修饰我们的控制器操作,其中覆盖OnAuthorization方法以在适当时将用户重定向到正确的控制器,如下所示。 (来自伟大的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;
    }
}

我尝试过使用新的RedirectResultRedirectToRouteResult,由于路由冲突,我们都没有按照我的意愿工作。有没有办法将AuthorizationContext.Result设置为一个值,以便我们执行当前未执行的操作? (作为最后的手段,我可​​以在移动路线上加上某种命名空间变量的前缀,但我还是想避免走这条路。)


我的问题也可以通过查看维基百科的桌面/移动路由来概括。他们的两个网站http://en.m.wikipedia.org/wiki/Main_Pagehttp://en.wikipedia.org/wiki/Main_Page也分享相同的路线,但是,根据您所处的模式,会返回截然不同的结果。

是否有可能在MVC项目中设置维基百科的路由,其中​​每个环境(移动/桌面)都在自己的区域注册?

2 个答案:

答案 0 :(得分:2)

一位同事使用自定义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()
    }
);

答案 1 :(得分:1)

不使用标准MVC路由。您可以使用属性路由,可以使用MVC 5或nuget包,AttributeRouting。