Giox
Giox

Reputation: 5123

Get the requested version of WebApi inside the controller

I've added the versioning of the WebAPI in an Asp.NET Core 3 WebApi project:


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

So now in my controller I can add the version:


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

    }
}

The issue is that in the API response sometimes I include also links to other endpoints. For example:

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

which, after adding the versioning that is required, doesn't work anymore.

I would like to retrieve in the methods of the controller the version requested by the user so that I can including in the link I build to other endpoints.

I can't hardcode because I could have a situation where one method is valid for several versions:

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

}

The JSON output example is:

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

So the field "originalCsvFile": "https://localhost:44322/Surveys/ExportToCSV?surveyID=19" should include also the version number

Upvotes: 3

Views: 6256

Answers (1)

scharnyw
scharnyw

Reputation: 2686

Starting from v3 of Microsoft.AspNetCore.Mvc.Versioning, You can get the version information injected into your controller method:

[HttpGet]
[ApiVersion("1.0")]
[ApiVersion("2.0")]
public ActionResult Get(ApiVersion version, int adm0Code = 0, int page = 1)
{
    // version is available here
}

See the docs on Github.

Upvotes: 10

Related Questions