.NET MVC 3 Routes

本文关键字:Routes MVC NET | 更新日期: 2023-09-27 18:10:19

最近我已经完成了从Web Forms到MVC 3的过渡,我一直在努力掌握MVC路由。我有一个有点特殊的问题,当我收到请求到我的应用程序(例如subdomain1.organisation.com或subdomain2.organisation.com),我希望默认路由使用如下:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
);

然而,当我的应用程序通过特定的子域(例如subdomain3.organisation.com)接收请求时,我希望应用程序默认为特定的控制器。我一直在以下代码:

http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing。aspx

应该是我想要的。所以我的全局代码。内容如下:

routes.Add("DomainRoute", new DomainRoute(
    "subdomain3.organisation.com", // Domain with parameters
    "{action}/{id}",    // URL with parameters
    new { controller = "Subdomain3Controller", action = "Index", id = "" }
));
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

部署后,当使用Subdomain3Controller将请求发送到subdomain3.organisation.com时,我的应用程序行为正确。但是,当访问任何其他子域时,例如localhost/Subdomain3Controller/Index,我的应用程序似乎选择了不正确的路由。

我的表单帮助器似乎返回了一个不正确的值:

ViewContext.Controller.ValueProvider.GetValue("controller").AttemptedValue
@using(Html.BeginForm(ViewContext.Controller.ValueProvider.GetValue("action").AttemptedValue, ViewContext.Controller.ValueProvider.GetValue("controller").AttemptedValue, FormMethod.Post, new Dictionary<string, object> {{ "id", "formid" } })){

知道为什么会这样吗?对于这个问题,任何人能提供的任何启示,我都将不胜感激。

提前感谢。

.NET MVC 3 Routes

您是否尝试过路由调试器,它旨在帮助调试这类问题

看起来现在也可以通过Nuget安装了

我还注意到,如果将控制器名称硬编码到BeginForm帮助器中,仍然会返回不正确的操作值:

      using (Html.BeginForm("Index", "Subdomain3Controller", FormMethod.Post, new Dictionary<string, object> { { "id", "formid" } }))
        {

生成:

<form id="formid" method="post" action="/">

而不是:

 <form id="formid" method="post" action="/Subdomain3Controller">
观看时

:

http://localhost/Subdomain3Controller/或http://localhost/Subdomain3Controller/Index

偶然发现了一个类似的问题,并设法找到了这个问题的解决方案。我知道这可能对原作者没有帮助,但它可能会帮助其他通过搜索到这里的人。

无论如何,似乎路由名称"Default"并没有增加多少权重。当BeginForm构造它的URL时,它从路由集合中选取"合适"的第一个路由。我没有深入挖掘这一切的内部工作原理。

我解决这个问题的方法是给子域路由添加一个约束,这样它只能用于Subdomain3Controller,如下所示:

        var domainRoute =  new DomainRoute(
            "subdomain3.organisation.com", // Domain with parameters
            "{action}/{id}",    // URL with parameters
            new { controller = "Subdomain3Controller", action = "Index", id = "" }
        );
        domainRoute.Constraints = new RouteValueDictionary();
        webserviceRoute.Constraints.Add("Controller", "Subdomain3Controller");
        routes.Add("DomainRoute", domainRoute);

[编辑]在思考了这个问题之后,我意识到我的情况和原来的海报有点不同。上面的方法不起作用,因为控制器已经不在URL内部了。

一种解决方案可能是交换路由的顺序,并为子域添加一个notqual约束到默认路由。如http://stephenwalther.com/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx所述(/编辑)