如何在ASP MVC中路由它

时间:2012-08-17 14:19:37

标签: asp.net-mvc asp.net-mvc-routing

这是我的第一个ASP MVC项目,所以我不知道该怎么做。

我有一个名为Admin的部分,它有一个Admin控制器。我只是将它用于索引页面。

在“管理”部分中,有不同的部分。让我们说公司和业务线

我想处理他们自己的CompanyController和LineOfBusinessController

中的所有内容

我希望路由以Admin为前缀,即。 Admin / Company,Admin / Company / Add

我通过在默认路由之前添加一个路径来实现这个目标

routes.MapRoute(
            name: "Admin",
            url: "Admin/{controller}/{action}/{id}",
            defaults: new { controller = "Admin", action = "Index", id = UrlParameter.Optional }
        );

问题是现在我的所有路线都选择了这个默认值,这意味着其他一切都变成了Admin / Section即Admin / Home等......

我尝试使用Html.RouteLink而不是ActionLink,并且URL的格式正确,但是当我去管理员/公司时它无法找到,因为它假设公司在AdminController中

如何妥善路由?

修改

这是我的路线,然后是我的链接

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        routes.MapRoute(
            name: "Admin",
            url: "Admin/{controller}/{action}/{id}",
            defaults: new { controller = "Admin", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );            
    }

链接

<li>@Html.ActionLink("Home", "Index", new { controller = "Home" }, ViewBag.SelectedNav == "Home" ? new { @class = "active" } : null)</li>

链接结束/ Admin / Home

更新

在我最终探索并最终使用区域时,没有在这里标记答案。在一个答案中建议,但其余的答案是不正确的,所以我不想误导任何人。感谢区域建议

2 个答案:

答案 0 :(得分:0)

在您的特定路由下方使用通用路由。路由定义的顺序很重要。当MVC为请求找到匹配的路由时,它将不处理其余的路径。

routes.MapRoute(
            name: "Admin",
            url: "Admin/{controller}/{action}/{id}",
            defaults: new { controller = "Admin", action = "Index", 
                                               id = UrlParameter.Optional }
        );

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

此情况下,您最好使用区域。如果您想将structure应用程序放入管理员/普通用户等不同部分,这是一种更好的方法。

答案 1 :(得分:0)

由于我不知道链接行为应该是什么,我建议的最好的方法是调试路由并查看哪条路由正在处理哪个URL。

1)进入Visual Studio并安装RouteDebugger

  

PM&GT; Install-Package routedebugger

2)在您的全局文件中添加一些代码

protected void Application_Start(object sender, EventArgs e)
{
  RegisterRoutes(RouteTable.Routes);
  RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
}

3)运行您的网站并请求您可疑的链接。

4)检查结果并相应修改


修改:好像RouteDebugger v2现在是RouteMagic

  

PM&GT;安装包RouteMagic

您可以在github

上找到源代码