【问题标题】:Creating custom URL routing that separates admin section from other sections of a website创建自定义 URL 路由,将管理部分与网站的其他部分分开
【发布时间】:2015-01-03 13:30:47
【问题描述】:

我想在 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";
   }
}

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多