ASP.NET MVC 6中属性路由正则表达式约束出错

时间:2016-03-15 12:40:35

标签: c# regex asp.net-core asp.net-core-mvc asp.net-core-1.0

我添加以下路由属性:

[HttpGet]
[Route("add")]
[Route(@"{id:int}/{inn:regex(^[0-9]+$)}/incBalance:range(0,1)/{dateSet:datetime}/{dateNext:datetime}")]
public IActionResult Add(int id, string inn, int incBalance, DateTime dateSet, DateTime dateNext)
{
  ....
}

执行时发生错误:

An unhandled exception occurred while processing the request.

InvalidOperationException: The following errors occurred with attribute routing information:

Error 1:
For action: 'WebProject.Areas.DAS.Controllers.ReportController.Add'
Error: While processing template 'das/report/[action]/{id:int}/{inn:regex(^[0-9]+$)}/incBalance:range(0,1)/{dateSet:datetime}/{dateNext:datetime}', a replacement value for the token '0-9' could not be found. Available tokens: 'action, area, controller'.

我删除了regex(^[0-9]+$),一切正常

1 个答案:

答案 0 :(得分:3)

RouteAttribute中使用正则表达式时,您必须使用[]转义[[]]个字符,因为[和{ {1}}保留用于控制器参数(动作,控制器和区域),如]

更新:同样适用于[Route("api/[controller]/[action]")]{,您可以使用}{{将其转义,但这个也适用于您在}}中设置的默认路由。