在控制器内获取WebApi的请求版本

问题描述 投票:0回答:1

我已经在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...
}

所以现在可以在我的控制器中添加版本:


[Route("[controller]")]
[ApiController]
public class SurveysController : ControllerBase
{
    [HttpGet]
    [ApiVersion("1.0")]
    public ActionResult Get(int adm0Code = 0, int page = 1)
    {

    }
}

问题在于,有时我在API响应中还包括指向其他​​端点的链接。例如:

OriginalCsvFile = (s.SurveyStatusID==2) ? (baseUrl + "/Surveys/ExportToCSV?surveyID="+ s.SurveyID) : ""

添加了所需的版本后,将无法再使用。

我想在控制器的方法中检索用户请求的版本,以便可以将自己构建的链接包含到其他端点中。

我无法硬编码,因为我可能会遇到一种方法对多个版本均有效的情况:

[HttpGet]
[ApiVersion("1.0")]
[ApiVersion("2.0")]
public ActionResult Get(int adm0Code = 0, int page = 1)
{

}

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"
    },
    ...
}

因此,字段“ originalCsvFile”:“ https://localhost:44322/Surveys/ExportToCSV?surveyID=19”还应包括版本号

c# asp.net-core asp.net-web-api versioning
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.