如果 URL 包含至少一个减号,则在 MVC 中验证 MapRoute
Validate MapRoute in MVC if URL contains at least one minus sign
我正在使用 MVC,我想向路由添加约束并仅在 URL 看起来像这样时才进行验证:
mysite/example-of-url-with-minus-sign
所以我需要这样的东西:
routes.MapRoute(name: "Categories",
url: "{category}",
defaults: new { controller = "Home", action = "Category" },
constraints: new { category = @"[-]+" }
);
您可以这样定义约束:
routes.MapRoute(
name: "DefaultWithMinus",
url: "{cat}",
defaults: new { controller = "Home", action = "WithMinus", cat = UrlParameter.Optional },
constraints: new { cat = @"\w*-+\w*" }
);
HomeController 中的动作
public ActionResult WithMinus(string cat)
{
return Content($"With Minus: {cat}");
}
结果:
http://localhost:49651/- => With Minus: -
http://localhost:49651/asdfds- => With Minus: asdfds-
http://localhost:49651/asdfds-sdfg => With Minus: asdfds-sdfg
http://localhost:49651/-sdfg => With Minus: -sdfg
Obs.: 此路由仅处理一个级别,因此如果您使用 www.site.com/fasdf-sadfsd/secondlevel 之类的东西,它将失败。
Obs².: 如果你需要更具体的东西,你应该创建你的自定义路由约束:http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/creating-a-custom-route-constraint-cs
我正在使用 MVC,我想向路由添加约束并仅在 URL 看起来像这样时才进行验证:
mysite/example-of-url-with-minus-sign
所以我需要这样的东西:
routes.MapRoute(name: "Categories",
url: "{category}",
defaults: new { controller = "Home", action = "Category" },
constraints: new { category = @"[-]+" }
);
您可以这样定义约束:
routes.MapRoute(
name: "DefaultWithMinus",
url: "{cat}",
defaults: new { controller = "Home", action = "WithMinus", cat = UrlParameter.Optional },
constraints: new { cat = @"\w*-+\w*" }
);
HomeController 中的动作
public ActionResult WithMinus(string cat)
{
return Content($"With Minus: {cat}");
}
结果:
http://localhost:49651/- => With Minus: -
http://localhost:49651/asdfds- => With Minus: asdfds-
http://localhost:49651/asdfds-sdfg => With Minus: asdfds-sdfg
http://localhost:49651/-sdfg => With Minus: -sdfg
Obs.: 此路由仅处理一个级别,因此如果您使用 www.site.com/fasdf-sadfsd/secondlevel 之类的东西,它将失败。
Obs².: 如果你需要更具体的东西,你应该创建你的自定义路由约束:http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/creating-a-custom-route-constraint-cs