如何在 MVC 4 中自定义路由

How to customize route in MVC 4

我正在使用 MVC4 处理网站。 我的基本网络结构:

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

但是我们有一个页面需要访问 URL 作为:ABC.com/vairable。 如何配置。 我配置如下:但需要打开 URL: ABC.com/Make/vairable:

        routes.MapRoute(


     "New",
        "Make/{PROMOTION_NAME}",
        new { controller = "Redeem", action = "MakeRedeem", PROMOTION_NAME = UrlParameter.Optional }, 
             null,
             new[] {"Project.Web.Controllers"});

We have one page need to access with URL as: ABC.com/vairable

基本上有 3 个选项,但我无法举出示例,因为您没有包含任何有关 "variable" 中预期内容的信息。

  1. 使用 RegEx route constraint.
  2. 使用 custom route constraint.
  3. 创建自定义 RouteBase 子类。参见

您需要对您的角色进行自定义约束。并在默认角色之前添加您的角色。自定义约束可防止匹配所有 URL 用户键入的内容并过滤不相关的 URL,以便其他角色可以匹配它们。考虑一下:

public class MyCatConstraint : IRouteConstraint
{
    // suppose this is your promotions list. In the real world a DB provider 
    private string[] _myPromotions= new[] { "pro1", "pro2", "pro3" };

    public bool Match(HttpContextBase httpContext, Route route, 
         string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
         // return true if you found a match on your pros' list otherwise false
         // In real world you could query from DB 
         // to match pros instead of searching from the array.  
         if(values.ContainsKey(parameterName))
         {
              return _myPromotions.Any(c => c == values[parameterName].ToString());
         }
         return false;
     }
}

现在在 MyConstraint 的默认角色之前添加一个角色:

routes.MapRoute(
    name: "promotions",
    url: "{PROMOTION_NAME}",
    defaults: new { controller = "Redeem", action = "MakeRedeem" },
    constraints: new { PROMOTION_NAME= new MyCatConstraint() },
    namespaces: new[] {"Project.Web.Controllers"}
);

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

现在 URL example.com/pro1 映射到 Redeem.MakeRedeem 操作方法,但 example.com/admin 映射到 Admin.Index