Gio*_*iox 3 c# versioning asp.net-web-api asp.net-core
我在 Asp.NET Core 3 WebApi 项目中添加了 WebAPI 的版本控制:
public void ConfigureServices(IServiceCollection services)
{
services.AddApiVersioning(
options =>
{
// reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions"
options.ReportApiVersions = true;
});
services.AddVersionedApiExplorer(
options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
...other configs...
}
Run Code Online (Sandbox Code Playgroud)
所以现在在我的控制器中我可以添加版本:
[Route("[controller]")]
[ApiController]
public class SurveysController : ControllerBase
{
[HttpGet]
[ApiVersion("1.0")]
public ActionResult Get(int adm0Code = 0, int page = 1)
{
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,在 API 响应中,有时我还包含指向其他端点的链接。例如:
OriginalCsvFile = (s.SurveyStatusID==2) ? (baseUrl + "/Surveys/ExportToCSV?surveyID="+ s.SurveyID) : ""
Run Code Online (Sandbox Code Playgroud)
添加所需的版本控制后,它不再起作用。
我想在控制器的方法中检索用户请求的版本,以便我可以将其包含在我构建的到其他端点的链接中。
我无法硬编码,因为我可能会遇到一种方法对多个版本有效的情况:
[HttpGet]
[ApiVersion("1.0")]
[ApiVersion("2.0")]
public ActionResult Get(int adm0Code = 0, int page = 1)
{
}
Run Code Online (Sandbox Code Playgroud)
JSON 输出示例是:
{
"page": 1,
"items": [
{
"surveyID": 19,
"surveyStatusID": 2,
"surveyCreateDate": "2020-05-21T11:51:15.853",
"surveyStartDate": "2020-05-04T00:00:00",
"surveyEndDate": "2020-05-08T00:00:00",
"surveyValidationReport": "Minimum required fields 145",
"countryName": "Afghanistan",
"adm0Code": 1,
"originalCsvFile": "https://localhost:44322/Surveys/ExportToCSV?surveyID=19"
},
...
}
Run Code Online (Sandbox Code Playgroud)
因此,字段 "originalCsvFile": " https://localhost:44322/Surveys/ExportToCSV?surveyID=19 " 还应包含版本号
sch*_*nyw 10
从 v3 开始Microsoft.AspNetCore.Mvc.Versioning,你可以获取注入到你的控制器方法中的版本信息:
[HttpGet]
[ApiVersion("1.0")]
[ApiVersion("2.0")]
public ActionResult Get(ApiVersion version, int adm0Code = 0, int page = 1)
{
// version is available here
}
Run Code Online (Sandbox Code Playgroud)
请参阅Github 上的文档。
| 归档时间: |
|
| 查看次数: |
4860 次 |
| 最近记录: |