Question

I want to build a versioned WebApi into an existing MVC project so that my URLs could be

/api/v1/account
/api/v2/account

I do not use Areas at the moment but after some research I thought this could work for me but apparently you cannot nest Areas (Im currently using MVC4 but can upgrade to 5).

How can I best achieve this?

Update

I ended up using this

Was it helpful?

Solution

There are two ways to achieve versioning with Web API

Method 1 :

/api/accountv1/
/api/accountv2/

The simplest way I found in versioning your API is to create an identical controller of "AccountV1Controller" and name it "AccountV2Controller", notice the suffix V1 and V2 in controller name, we’ll depend on this part to select the appropriate controller based on API version.

Method 2 :

/api/v1/account
/api/v2/account

Or you could play with Routes to get the same behaviour

config.Routes.MapHttpRoute(
    name: "1-0Api",
    routeTemplate: "api/v1/Account/{id}",
    defaults: new { controller = "AccountV1", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
    name: "2-0Api",
    routeTemplate: "api/v2/Account/{id}",
    defaults: new { controller = "AccountV2", id = RouteParameter.Optional }
);

Taken from here

OTHER TIPS

Here are two approaches that would not require you to have 2 separate Controller classes.


Request Headers

One of the recommended versioning designs is to use request headers instead of URL parameters.

if (Request.Headers["API Version"] == "2")
{
    return Version2Code();
}
return Version1Code();

Use a RouteContraint

You could also use a route contraint too:

config.Routes.MapHttpRoute(
    name: "versionedApi",
    routeTemplate: "api/{version}/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional },
    constraints: new {version = @"^[vV]\d+$"}
);

Then version would become a route function parameter just like id.

public class AccountController: Controller {

    public class ActionResult Index(object id, string version)
    {
       if (string.Equals(version, "v2", StringComparison.OrdinalIgnoreCase))
       {
          return Version2Code();
       }
       return Version1Code();
    }
}

Also, check out Web API 2 Attribute Routing

Also, if you do upgrade to Mvc 5 and WebAPI 2, there are examples of how to do this with Attribute Routing http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top