2

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 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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")]
Thanks for the gist! I wonder how the number matching in the controller class name works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.