如何在MVC中创建自定义路由

本文关键字:创建 自定义 路由 MVC | 更新日期: 2023-09-27 18:19:28

我有一个名为Admin的区域,其模型名为CMSPage。我的控制器名为CMSPagesController。我想创建一个自定义路由,这样我就可以简单地使用Page而不是CMSPage,所以我认为通过创建以下自定义路由,它会起作用,但没有:

routes.MapRoute(
    "AdminPages",
    "Admin/Pages/{action}/{id}",
    new { controller = "CMSPages", action = "Index", id = UrlParameter.Optional }
);

有人能把我带向正确的方向吗?

如何在MVC中创建自定义路由

using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication1
{
public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            "Blog",                                           // Route name
            "Archive/{entryDate}",                            // URL with parameters
            new { controller = "Archive", action = "Entry" }  // Parameter defaults
        );
        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with        parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );
    }
    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
}

}

添加到路线表中的路线顺序很重要。我们新的自定义博客路线添加在现有的默认路线之前。如果颠倒了顺序,则将始终调用默认路由,而不是自定义路由。

自定义博客路由匹配任何以/Archive/开头的请求。因此,它匹配以下所有URL:

/档案/12-25-2009

/档案/10-6-2004

/档案/苹果

自定义路由将传入请求映射到名为Archive的控制器,并调用Entry()操作。当调用Entry()方法时,条目日期将作为名为entryDate的参数传递。

我很抱歉。我忘了还有区域注册过程。问题是,我想从创建该控制器的区域访问该控制器(Admin)。因此,必须在那里进行自定义路线注册。不在我的RouteConfig.cs中(见下文)。感谢你的回复Neeraj,你的回答没有错,只是对我关于某个领域的问题不正确。

using System.Web.Mvc;
namespace WebApplication1.Areas.Admin
{
    public class AdminAreaRegistration : AreaRegistration 
    {
        public override string AreaName 
        {
            get 
            {
                return "Admin";
            }
        }
        public override void RegisterArea(AreaRegistrationContext context) 
        {
            // This is where the custom route has to be registered for me to access
            // it from my area.
            context.MapRoute(
                "Admin_pages",
                "Admin/Pages/{action}/{id}",
                new { action = "Index", 
                      controller = "CMSPages", 
                      id = UrlParameter.Optional }
            );
            context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}