创建自定义URL路由,将管理部分与网站的其他部分分开

时间:2014-11-06 21:27:10

标签: asp.net-mvc url routes asp.net-mvc-5

我想在ASP.NET MVC 5项目中创建一个具有常量路径的自定义URL路由。 例如,我想要" www.mysite/admin/controller/action/" admin是一个常数。我也有一些路线。

之后,我想在浏览器中输入admin/controller/action/时定义一个策略,定向到管理面板,否则如果URL中不存在admin/,则定向到常规页面。 为实现这一目标,我在_ViewStart.cshtml编写了一些代码,但需要进行一些改革。

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

        routes.MapRoute(
           name: "Tag",
           url: "Tags/{tag}/{page}/{id}",
           defaults: new { controller = "Article", action = "Index", tag = (string)null, id = UrlParameter.Optional, page = @"/d" }
           );

        routes.MapRoute(
          name: "Tags",
          url: "Tags/",
          defaults: new { controller = "Tag", action = "Index" }
          );

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

        routes.MapRoute(
            null,
            "Page{page}",
            new { Controller = "Article", action = "Index" },
            new { page = @"/d" }
            );
}

_ViewStart.cshtml:

@{
   if (HttpContext.Current.User.IsInRole("Administrator"))
   {
       // ??? need some codes for directing just to the /admin part
       Layout = "~/Views/Shared/_AdminLayout.cshtml";
   }
   else
   {
       Layout = "~/Views/Shared/_Layout.cshtml";
   }
}

1 个答案:

答案 0 :(得分:4)

您可以在MVC应用程序中使用管理员Area,这将拥有自己的路由。请在此处查看此链接,以获取有关Using Areas的帮助。您的路线可能如下所示......

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}