Hello i have a controller and i want to version its routes.However i do not want the api-version to be added in the querystring but in the begining of the url , after the controller name:
Typical Path: /api/admin/get-computer/1
Versioned Path: /api/admin/V[version]/get-computer/1
I do not understand how to configure the controller and the UseMvc
extension from the Startup
:
[ApiVersion("1.0")]
[ApiVersion("2.0")]
[Route("/api/admin")]
public class AdminController : Controller {
[HttpGet]
[MapToApiVersion("1.0")]
[Route("/get-computer")]
public async Task<ActionResult<Catalog>> GetComputerAsync1(int id) {
return null;
}
[HttpGet]
[MapToApiVersion("2.0")]
[Route("/get-computer")]
public async Task<ActionResult<Catalog>> GetCatalogAsync2(int id) {
return null;
}
}
Startup
public void Configure(IApplicationBuilder app) {
app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=Admin}/V[???]/{action=Index}/{id?}");
});
}
Preferred usage
"/api/admin/V1/get-computer/3"
"/api/admin/V2/get-computer/4"
How can i achieve this ? What is the supposed form of the route template in the UseMvc
extension ?
Install the package Microsoft.AspnetCore.Mvc.ApiVersioning (if you havent already done so).
Configure the versioning services in your Startup -> ConfigureServices(...) by adding this:
services.AddApiVersioning();
Then in your [Route()]
attribute on your controller insert the api version parameter as follows:
[Route("api/v{version:apiVersion}/admin")]
This enables your controller to be hit with urls like "api/v1.0/admin". You can remove the 'v' before the {version} parameter if you do not want it.
For further details let me refer you to the documentation on url versioning