如何使用ASP.NET Core特性路由获取端点后的完整路径
ASP.NET Core 多级路径路由匹配问题
我对ASP.NET Core路由非常陌生。我正在原型开发的系统中有类似字典的字符串与关联名称映射:
/dev/accounting/people= "people string"/test/it/documents= "some it document string"/some/arbitrary/name/separated/by/slashes= "some other string"
我希望创建一个API端点,可通过以下方式访问:
http://mysite/api/GetString/dev/accounting/peoplehttp://mysite/api/GetString/test/it/documentshttp://mysite/api/GetString/some/arbitrary/name/separated/by/slashes
当前代码
Dictionary<string, string> _stringDictionary = new Dictionary<string, string>() { { "/abc", "this works" }, { "/abc/def", "this doesn't" }, { "/abc/def/ghi", "neither does this" }, { "/some/arbitrary/name/separated/by/slashes", "nor this"}, }; [Route("api/GetString/{objectPath}")] [HttpOptions] [HttpGet] public IActionResult GetString(string objectPath) { // -http://mysite/api/GetString/abc this works // -http://mysite/api/GetString/abc?param1=2¶m2=3 this does too // -http://mysite/api/GetString/abc/def nope // -http://mysite/api/GetString/some/arbitrary/name/separated/by/slashes?param1=2¶m2=3 nope // I want objectPath to be everything after 'getstring' in the URLs above EXCEPT the parameters string resultValue = "[[NOT FOUND]]"; if (_stringDictionary.ContainsKey(objectPath)) resultValue = _stringDictionary[objectPath]; return new OkObjectResult(new { result = resultValue, }); }
目前的问题是:只能匹配1-2级路径,多级路径请求会返回404,需要让objectPath获取GetString之后的所有路径部分(不含查询参数)。
解决方案
问题根源在于默认路由参数{objectPath}只能匹配单个路径段(斜杠之间的内容)。要捕获多级路径,需要在路由参数后添加通配符:
方式1:使用*匹配剩余所有路径
修改路由模板为:
[Route("api/GetString/{*objectPath}")]
*会捕获GetString之后的所有路径内容(包括斜杠),比如访问/api/GetString/abc/def时,objectPath的值为abc/def。
由于你的字典键带前导斜杠,需要在代码中拼接前导斜杠后再匹配:
[Route("api/GetString/{*objectPath}")] [HttpOptions] [HttpGet] public IActionResult GetString(string objectPath) { string fullPath = $"/{objectPath}"; string resultValue = "[[NOT FOUND]]"; if (_stringDictionary.ContainsKey(fullPath)) resultValue = _stringDictionary[fullPath]; return new OkObjectResult(new { result = resultValue, }); }
注意事项
- 查询参数会被自动忽略,路由仅捕获路径部分,无需额外处理。
- 如果字典键不带前导斜杠,直接使用
objectPath匹配即可。
内容的提问来源于stack exchange,提问作者Kerry Thomas
相关产品推荐
相关产品推荐

