简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM