WebAPI 正则表达式路径属性抛出错误“找不到令牌的替换值"; [英] WebAPI Regex path attribute throws error "Replacement value for the token could not be found"
问题描述
在我的 .NEt Core 3 代码中,我使用以下参数定义了一个 WebAPI 路由:
In my .NEt Core 3 code I have defined a WebAPI route using the following parameter:
[HttpGet("ViewerRoles/{searchString:regex(^\\d+-(?<=-)[\\w ]*$)}")]
public async Task<ViewerRole> GetViewSettings(string searchString) {
// ....
}
这会在启动服务时引发以下错误:
This throws me the following error when starting the service:
错误:处理模板时'api/[控制器]/ViewerRoles/{searchString:regex(^\d+-(?<=-)[\w]*$)}',无法找到标记 '\w ' 的替换值.可用令牌:动作,控制器".使用 '[' 或 ']' 作为路由或约束中的文字字符串,使用 '[[' 或 ']]'相反."
Error: While processing template 'api/[controller]/ViewerRoles/{searchString:regex(^\d+-(?<=-)[\w ]*$)}', a replacement value for the token '\w ' could not be found. Available tokens: 'action, controller'. To use a '[' or ']' as a literal string in a route or within a constraint, use '[[' or ']]' instead."
我很困惑.正则表达式似乎是正确的,并且适用于各种在线测试人员.但是为什么它会抛出错误呢?
I'm pretty confused. The Regex seems to be correct and works in various online testers. But why does it throw an error then?
推荐答案
我在复习时已经找到了答案.有问题的部分是 [\\w ]
.您必须使用双方括号.否则编译器会将其解释为占位符.
I already found the answer as I was reviewing it. The problematic part is [\\w ]
. You have to use double square brackets. Otherwise the compiler will interpret it as a placeholder.
[HttpGet("ViewerRoles/{searchString:regex(^\\d+-(?<=-)[[\\w ]]*$)}")]
public async Task<ViewerRole> GetViewSettings(string searchString) {
// ....
}
这篇关于WebAPI 正则表达式路径属性抛出错误“找不到令牌的替换值";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!