Home > Net >  Controller route not found if it contains a version
Controller route not found if it contains a version

Time:10-13

I am having issues when trying to route to a Controller when it is included via a external project. The controller in question works fine when included directly in the project or from the external project ONLY when the version field is removed from the route. The controller is defined as below.

[ApiController]
[ApiVersion("1.0")]
[Produces("application/json")]
[Route("api/v{version:apiVersion}/devices")]
[Authorize(Roles = UserConst.PermissionGroup.Admin)]
public class DeviceManagementController : ControllerBase{...}

Changing the route to the below works correctly

[Route("api/devices")]

Changing the route to the below fails the same way as including it through {version:apiVersion}

[Route("api/v1.0/devices")]

Any ideas on what could be wrong? With any version info the server just seems to return the default Index page which is the fallback when a controller cannot be found.

Startup.cs code for adding Api versioning

services.AddApiVersioning(config =>
{
    config.DefaultApiVersion =
      new ApiVersion(1, 0);
   config.AssumeDefaultVersionWhenUnspecified = true;
   config.ReportApiVersions = true;
});

CodePudding user response:

I've done some testing.

Af first I added [Route("api/devices")] to your controller attributes

[ApiController]
    [ApiVersion("1.0")]
    [Produces("application/json")]
    [Route("api/v{version:apiVersion}/devices")]
    [Route("api/devices")]
    public class DeviceManagementController : ControllerBase 

and found that url .../api/v1.0/devices works properly.

After this I tryed to use just .../api/devices url.

  1. It was working properly with [ApiVersion("1.0")] attribute

  2. It issued a wrong version error when I changed attribute to [ApiVersion("2.0")]

so everything was working as it was expected.

Summary:

I recommend you to add [Route("api/devices")] and try to use.../api/devices url as a workaround for now, till you find out something better.

  • Related