我正在使用 Microsoft.AspNetCore.Mvc.Versioning
并且我在正确设置路由时遇到了困难。我正在关注 Hanselman 博客中的信息:http://www.hanselman.com/blog/ASPNETCoreRESTfulWebAPIVersioningMadeEasy.aspx
我想像这样通过 URI 访问我的 API:
http://me.com/api/v1.0/foo/bar
我的 foo 类有正确的属性:
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
以上工作正常,但如果我输入以下内容(无版本):
执行上述操作时出现 404(我假设是因为未针对未指定的版本正确设置路由)。
我尝试将其添加到 Startup.cs 文件中:
//Add the versioning
services.AddApiVersioning(o => {
//Everytime a new version is created this must be updated to default to the latest version.
o.AssumeDefaultVersionWhenUnspecified = true;
o.DefaultApiVersion = new ApiVersion(1, 0);
});
但这也不起作用 - 所以我将我想要的路由添加到我的 foo 类/ Controller 的顶部:
[Route("api/[controller]")]
这得到了我想要的行为,我可以访问下面的所有路由:
http://me.com/api/v1.0/foo/bar
这是应该的方式吗?为什么默认版本不像 Hanselman 描述的那样工作?
最佳答案
请注意,Scott 并未建议 URL 路径分段方法将允许您提供空白版本:
To be clear, you have total control, but the result from the outside is quite clean with /api/v[1|2|3]/helloworld
不支持在使用 URL 段映射时指定默认版本。看这个Github issue获取更多信息。
关于c# - Mvc.Versioning 构建路由的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42248570/