Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add versioning to existing WebAPI

I have an existing ASP.NET WebAPI project with a controller that looks like this:

namespace WebSite.WebApi.Controllers
{
    [RoutePrefix("api/accounts")]
    public class AgreementsController : ApiController
    {
        // GET ~/api/accounts/xxx
        [Route("{accountId}")]
        public IHttpActionResult Get(string accountId) => Ok( $"Account #{accountId} from default controller");
    }
}

I'm calling the action method by using this URL: /api/accounts/123

Now, I want to make another version of this controller that would be called if a client appends a certain query string parameter like this: /api/accounts/123?api-version=2. The first URL (without api-version param) should still lead to the initial controller

I thought I could use aspnet-api-versioning by Microsoft by making another controller and using ApiVersion attribute like this:

namespace WebSite.WebApi.Controllers.V2
{
    [ApiVersion("2")]
    [RoutePrefix("api/accounts")]
    public class AgreementsController : ApiController
    {
        // GET ~/api/accounts/xxx?api-version=2
        [Route("{accountId}")]
        public IHttpActionResult Get(string accountId) => Ok($"Account #{accountId} from V2 controller");
    }
}

But it doesn't seem to work like that. All the samples on GitHub suggest that I should decorate both my controllers with ApiVersion attribute and explicitly use version in both URLs: /api/accounts/123?api-version=1 and /api/accounts/123?api-version=2.

But I need the URL for the 1st controller to remain the same as it is now: /api/accounts/123. Is there any way to achieve this with aspnet-api-versioning library? Or is there some other API versioning library that can accomplish this task?

like image 268
Andre Borges Avatar asked Oct 23 '25 17:10

Andre Borges


1 Answers

This is possible, you just need to tell the versioning framework to assume a version if you don't specify one in the config:

public static void Register(HttpConfiguration config)
{
    config.AddApiVersioning(versioningConfig =>
    {
        versioningConfig.AssumeDefaultVersionWhenUnspecified = true;
    });

    //snip
}
like image 184
DavidG Avatar answered Oct 26 '25 07:10

DavidG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!