Mvc.Versioning 构建路由的正确方法
Mvc.Versioning correct way to build routes
我正在使用 Microsoft.AspNetCore.Mvc.Versioning
,但我在正确设置路线时遇到了困难。我正在关注 Hanselman 博客中的信息:http://www.hanselman.com/blog/ASPNETCoreRESTfulWebAPIVersioningMadeEasy.aspx
我想像这样通过 URI 访问我的 API:
http://me.com/api/v1.0/foo/bar
我的 foo 属性正确 class:
[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 的顶部 class/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。
我正在使用 Microsoft.AspNetCore.Mvc.Versioning
,但我在正确设置路线时遇到了困难。我正在关注 Hanselman 博客中的信息:http://www.hanselman.com/blog/ASPNETCoreRESTfulWebAPIVersioningMadeEasy.aspx
我想像这样通过 URI 访问我的 API:
http://me.com/api/v1.0/foo/bar
我的 foo 属性正确 class:
[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 的顶部 class/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。