Smithy
Smithy

Reputation: 2190

Mvc.Versioning correct way to build routes

I'm using Microsoft.AspNetCore.Mvc.Versioning and I'm having difficulty setting up the routes correctly. I'm following the info from Hanselman's blog here: http://www.hanselman.com/blog/ASPNETCoreRESTfulWebAPIVersioningMadeEasy.aspx

I want to access my API via URIs like so:

http://me.com/api/v1/foo/bar

http://me.com/api/v1.0/foo/bar

I have the correct attributes on my foo class:

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]

The above works OK, but if I type the below (no version):

http://me.com/api/foo/bar

I get a 404 when going to the above (I assume because the route is not setup correctly for no version specified).

I tried adding this to the Startup.cs file:

//Add the versioning
services.AddApiVersioning(o => {
       //Everytime a new version is created this must be updated to default to the latest version.
       o.AssumeDefaultVersionWhenUnspecified = true;
       o.DefaultApiVersion = new ApiVersion(1, 0);
});

But this didn't work either - so I then added the route I wanted to the top of my foo class/controller:

[Route("api/[controller]")]

This gets the desired behavior I want and I can access all routes below:

http://me.com/api/v1/foo/bar

http://me.com/api/v1.0/foo/bar

http://me.com/api/foo/bar

Is this the way it should be done? Why isn't the default version working the way Hanselman describes?

Upvotes: 1

Views: 1110

Answers (1)

DavidG
DavidG

Reputation: 119116

Note that Scott doesn't suggest that the URL path segmenting method will allow you to give a blank version:

To be clear, you have total control, but the result from the outside is quite clean with /api/v[1|2|3]/helloworld

Having default version specified when using URL segment mapping is not supported. See this Github issue for more information.

Upvotes: 3

Related Questions