2
votes

I am trying to implement versioning using AttributeRouting in WEB API. I have defined two folders under Controllers called v1 and v2. I have multiple controllers in each folder. In the Product Controller I define the

RoutePrefix as [RoutePrefix("v1/product")] and [RoutePrefix("v2/product")]

When I go to the URI v1/product it works fine, however v2/product also executes the code in v1 folder. Does attribute routing support versioning or do I have to do something related to Routes as well. My route is defined as

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{namespace}/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional}
        );

My product controller looks like

namespace API.Controllers
{

[RoutePrefix("v1/product")] 

public class Productv1Controller : ApiController

{

    private DBContext db = new DBContext(); 


    public dynamic Get()
    {
       //Gets the Products
    }
}

The code in the V2 product is

namespace API.Controllers
{

[RoutePrefix("v2/product")] 

public class Productv2Controller : ApiController

{

    private DBContext db = new DBContext(); 


    public dynamic Get()
    {
       //Gets the Products
    }
}

Can someone please suggest or provide a link to an example to implement versioning using Attribute Routing

1

1 Answers

4
votes

You need to decorate the actions with the Route attribute in order for it to work.

[Route] public dynamic Get() ...

Also, you need to have config.MapHttpAttributeRoutes(); in the WebApiConfig's Register method

update

Here's a link to the gist, I tested this in a new web application with WebApi 5 and it worked. https://gist.github.com/DavidDeSloovere/11367286