c# - 不以某些文字开头的 ASP.NET MVC 路由

标签 c# .net asp.net-mvc

我需要为不是从某些文字开始的 url 创建一个路由。我创建了以下路由定义:

    routes.MapRoute("",
                    "{something}",
                    new { Controller = "Home", Action = "Index" },
                    new
                        {
                            something = "^(?!sampleliteral)"
                        });

但是好像不行

最佳答案

您可以尝试使用路由约束:

public class MyConstraint: IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var value = values[parameterName] as string;
        if (!string.IsNullOrEmpty(value))
        {
            return !value.StartsWith("sampleliteral", StringComparison.OrdinalIgnoreCase);
        }
        return true;
    }
}

然后:

routes.MapRoute(
    "",
    "{something}",
    new { Controller = "Home", Action = "Index", something = UrlParameter.Optional },
    new { something = new MyConstraint() }
);

关于c# - 不以某些文字开头的 ASP.NET MVC 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4415890/

相关文章:

c# - C++/Java/C#图像处理库

c# - 由于缺少 .net 4.5 框架,多目标 .NET Standard 2.0 和 .NET 4.5 失败

c# - 如何对可为空的日期使用空合并运算符

c# - 如果您的 ViewModel 是 IDisposable,MVC 会调用 Dispose 吗?

c# - 如何阻止 ASP.NET Web API 隐式解释 HTTP 方法?

c# - IIS 中多个工作线程的共享消息队列

c# - C#读取特定的XML数据

c# - PostgreSQL 不保存完整的 DateTimeOffset

c# - .Net 列表 ForEach Item

c# - 错误 : '<method1>' and '<method2>' cannot overload each other