c# - 两个区域是否可以共享同一条路线并且仍然可以到达?

标签 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 装饰我们的 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;
    }
}

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


我的问题也可以通过查看维基百科的桌面/移动路由来总结。他们的两个网站,http://en.m.wikipedia.org/wiki/Main_Pagehttp://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/

相关文章:

c# - 我们应该使用 Eval 还是 Databind 事件?

c# - 通过 Ajax 发布到 MVC Controller

asp.net-mvc - 在 MVC 中提交后保留密码文本框值

asp.net-mvc - 将空值添加到 ASP.net MVC 中的 DropDownList

asp.net - 如何在ASP.NET MVC4中添加新页面?

C# WPF Web 浏览器控件 : How to use JavaScript

c# - 当枚举名称与类名称冲突时该怎么办?

c# - MVC 5 经过身份验证的用户正在注销,没有 "remember me"(ExpireTimeSpan/MachineKey/Session Timeout)

c# - 在 MVC Razor View 中按月分组

C#:在索引页中设置 HttpCookie 内容,然后在整个网站上消失