c# - Mvc.Versioning 构建路由的正确方法

标签 c# asp.net-web-api asp.net-core versioning

我正在使用 Microsoft.AspNetCore.Mvc.Versioning 并且我在正确设置路由时遇到了困难。我正在关注 Hanselman 博客中的信息:http://www.hanselman.com/blog/ASPNETCoreRESTfulWebAPIVersioningMadeEasy.aspx

我想像这样通过 URI 访问我的 API:

http://me.com/api/v1/foo/bar

http://me.com/api/v1.0/foo/bar

我的 foo 类有正确的属性:

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]

以上工作正常,但如果我输入以下内容(无版本):

http://me.com/api/foo/bar

执行上述操作时出现 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/foo/bar

http://me.com/api/v1.0/foo/bar

http://me.com/api/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/

相关文章:

c# - RegularExpressionAttribute 行为中的正则表达式

javascript - WebApi 重定向到外部站点

asp.net - Controller 调用另一个 Controller C# WebApi

debugging - 如何在 Visual Studio 2015 asp.net 5 中调试 Typescript?

C# 在 Linux 中运行 tesseract(或任何命令)

c# - mkbundle 生成的程序(来自 C# 程序)在 Ubuntu 上运行,但在 Redhat 上不起作用

c# - dotnet build xamarin 项目使用控制台失败

c# - ASP.NET Core HttpClient无法在容器中进行HTTPS调用

c# - 使用 C# MongoDB 驱动程序,如何序列化对象引用的集合?

javascript - 仅当对象的属性发生更改时,Angular 才更新 View