ASP.NET MVC 3 路由约束 : Regular Expression for not null

标签 asp.net asp.net-mvc regex asp.net-mvc-3 asp.net-mvc-routing

我正在尝试创建一个路线约束,但不确定什么是最好的。这是没有限制的路线:

context.MapRoute(
    "Accommodation_accomm_tags",
    "accomm/{controller}/{action}/{tag}",
    new { action = "Tags", controller = "AccommProperty" },
    new { tag = @"" } //Here I would like to put a RegEx for not null match
);

最好的解决方案是什么?

最佳答案

您能否创建一个IRouteConstraint:

public class NotNullRouteConstraint : IRouteConstraint
{
  public bool Match(
    HttpContextBase httpContext, Route route, string parameterName, 
    RouteValueDictionary values, RouteDirection routeDirection)
  {
    return (values[parameterName] != null);
  }
}

您可以连接:

context.MapRoute(
  "Accommodation_accomm_tags",
  "accomm/{controller}/{action}/{tag}",
  new { action = "Tags", controller = "AccommProperty" },
  new { tag = new NotNullRouteConstraint() }
);

关于ASP.NET MVC 3 路由约束 : Regular Expression for not null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7498347/

相关文章:

c# - 数据过滤的设计模式

c# - 使用 mimekit/mailkit 库获取电子邮件的传递状态

php - preg_replace 一个没有跟随特定字符的字符

php - 用于验证基于国际象棋的输入的正则表达式?

c# - 尽管指定了 .Returns,最小起订量对象仍返回 null

c# - 查询 Unity 的所有接口(interface)实例

c# - 以美国文化格式显示货币值

MySQL 和 ASP MVC - 存储表情符号字符

javascript - MVC : Dropdown Filter of Datatable interferes with UIHints

regex - 基本 Python 正则表达式 : re. DOTALL *not* 匹配新行