Michael Earls
Michael Earls

Reputation: 1557

Using custom route with versioning in ASP.NET Core 2.0

I use a custom middleware to change the Path used in a request to a WebApi.

In my middleware Invoke, I have:

// code prior to this extracts controller name and remaining path
var newPath = $"/{version}/{controller}/ToDoItemDto/{remainingPath}"; // ToDoItemDto was inserted by me and was not in the original request
context.Request.Path = newPath;
return _next(context);

In my ToDoController, I have:

[Route("api/v{version:apiVersion}/[controller]")]
// other attributes for the controller
public class TodoController : Controller
{
// ...
  [HttpGet("TodoItemDto/{primaryId}", Name="GetTodoById")]
  public IActionResult GetById(long primaryId)
  {
      // code here...
  }
}

However, when I attempt to access this controller, I get an Http 405 error with the following result:

{"error":{"code":"UnsupportedApiVersion","message":"The HTTP resource that matches the request URI 'http://localhost:1482/v1/todo/ToDoItemDto/1' does not support the API version '1'.","innerError":null}}

I tried adding the following attribute to my GetById() method:

[MapToApiVersion("1.0")]

but that did not help.

I searched the web and found a promising result on the GitHub page for the versioning Api. However, I don't understand the suggested fix (using an IActionResult) in this context.

Can custom route matching be done while also using versioning? If so, how?

Upvotes: 1

Views: 1021

Answers (1)

Marcus Höglund
Marcus Höglund

Reputation: 16846

You have missed to add api in the route. Try it this way

var newPath = $"api/{version}/{controller}/ToDoItemDto/{remainingPath}";

Upvotes: 2

Related Questions