c# - 我可以创建一个只接受 URL 中的大写字母的 ASP MVC 路由吗?

标签 c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-routing

我有以下路线:

context.MapRoute(
    "content",
    "{page}/{title}",
    new { controller = "Server", action = "Index" },
    new { page = @"^[AFL][0-9A-Z]{4}$" }
);

此路由用于以下页面:

/A1234
/F6789
/L0123

但是它也捕捉到:/Admin,这是我不想要的。

我采用了如下所示的临时解决方案:

context.MapRoute(
    "content",
    "{page}/{title}",
    new { controller = "Server", action = "Index" },
    new { page = @"^[AFL][0-9][0-9A-Z]{3}$" }
);

这只有效,因为现在我的所有页面的第二个数字都是 0。

有没有一种方法可以将我的路由配置为接受后跟 4 个大写字符的 A、F 或 L,但不捕获“dmin”?

不确定是否是这种情况,但我认为正则表达式不应该接受“dmin”,因为它是小写的,而且我只指定了 A-Z。但是,当用作 MVC 路由时,它确实采用“dmin”。有谁知道 ASP MVC 是否在内部将其转换为全部大写?

最佳答案

方案一:自定义路由约束类

默认路由处理在匹配 URL 时会忽略大小写(请参阅下面的代码),这就是您的案例中的 Admin 也匹配的原因。您应该做的就是编写一个实现 IRouteConstraint 接口(interface)的自定义路由约束类,并适本地实现 Match 方法以区分大小写。

Here's a tutorial to get you started

方案二:自定义Route

如果您查看默认的 Route 类如何处理约束,这是代码:

protected virtual bool ProcessConstraint(HttpContextBase httpContext, object constraint, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
    IRouteConstraint routeConstraint = constraint as IRouteConstraint;

    // checks custom constraint class instances
    if (routeConstraint != null)
    {
        return routeConstraint.Match(httpContext, this, parameterName, values, routeDirection);
    }

    // No? Ok constraint provided as regular expression string then?
    string text = constraint as string;
    if (text == null)
    {
        throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, SR.GetString("Route_ValidationMustBeStringOrCustomConstraint"), new object[]
        {
            parameterName,
            this.Url
        }));
    }
    object value;
    values.TryGetValue(parameterName, out value);
    string input = Convert.ToString(value, CultureInfo.InvariantCulture);
    string pattern = "^(" + text + ")$";

    // LOOK AT THIS LINE
    return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant);
}

最后一行实际上匹配提供的正则表达式路由约束。如您所见,它忽略了大小写。所以第二种可能的解决方案是编写一个新的 Route 类,它继承自这个默认的 Route 类,并将 ProcessConstraint 方法重写为 not 忽略大小写。然后其他一切都可以保持不变。

关于c# - 我可以创建一个只接受 URL 中的大写字母的 ASP MVC 路由吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13008904/

相关文章:

c# - 在 SPA 应用程序的 ASP.NET 5 中正确使用 AntiForgery token ?

c# - Unity 测试工具使用 GameObject 进行单元测试给出 "You are trying to create a MonoBehaviour using the ' new' 关键字。这是不允许的。”

c# - 如何将全局异常处理程序添加到 Metro Style 应用程序?

asp.net - 为什么在构建 View 时要指定数据上下文类?

asp.net-mvc - Webform 属性上的内联代码

html - 为什么 padding-bottom 无法向上移动元素?

c# - MVC 3 C# - 部署和 MYSQL 数据库

asp.net-mvc-3 - SelectList 中的本地化枚举字符串

c# - 为什么运算符方法在 C# 中应该是静态的?

asp.net-mvc - 从 Javascript 更新 Razor 模型