Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

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

share|improve this answer
    
I added the [Route("v1/product")] and [Route("v2/product")] to the GET method but it is still not working. It is always going to the /v1/product irrespective of the path specified in the ROUTE. –  user2515186 Apr 26 at 4:35
    
You should not repeat the prefix of the RoutePrefix attribute in the Route attribute. If you want to override the prefix, then you can do something like [Route("~v0/product")] –  Deef Apr 28 at 9:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.