Iria
Iria

Reputation: 185

change api routing of an specific endpoint

I have an api routing that works so far:

    config.Routes.MapHttpRoute(
        name: "MyApi",
        routeTemplate: "api/v1/{param}/string1/string2",
        defaults: new { controller = "MyApi", ... })

In the controller, I have a post method that works fine, but I need to modify it, which is fine and it does work. The problem is the following:

I need to leave the old version of the endpoint for compatibility purposes, creating a new endpoint with the following route: "api/v2/{param}/string1/string2". I deally, I would like to have them on the same controller (file), so I thought in using [Route("...")] but unfortunately, this only adds strings to the route, and what I need is to substitute v1 for v2 on the route, is there any way of doing this?

I thought in a workaround that is creating a new controller with the new route, same parameters, but it will have to be in another file, instead of keeping them together. Any suggestions or this is the only way of doing it? Thanks in advance. Unfortunately, target network is 4.7.2

Upvotes: 0

Views: 1403

Answers (1)

Tiny Wang
Tiny Wang

Reputation: 16066

Firstly, I don't think you can realize the version control only with some configurations but not adding a new method or new controller as I really failed to find it in official document. And if you insist on keep the method unique that you won't add a new method or file, you may take azure api management into consideration. It's a fantastic tool but a little expensive for production use.

And as you mentioned you can still control your code in the application, I recommend you to add some code to realize the version control. Here's a blog said about it. And it provides a similar way to realize your goal with the attribution [ApiVersion("1.0")] and [Route("api/{v:apiVersion}/employee")].

It also requires a nuget package Microsoft.AspNetCore.Mvc.Versioning, with the configuration in startup.cs

public void ConfigureServices(IServiceCollection services)  
{  
    services.AddControllers();  
    services.AddApiVersioning(x =>  
    {  
        x.DefaultApiVersion = new ApiVersion(1, 0);  
        x.AssumeDefaultVersionWhenUnspecified = true;  
        x.ReportApiVersions = true;  
    });  
}  

And this is my test result:

enter image description here

Upvotes: 2

Related Questions