简体   繁体   English

在ASP.NET Core 2.0中使用自定义路由和版本控制

[英]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. 我使用自定义中间件将请求中使用的路径更改为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: 在我的ToDoController中,我有:

[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: 但是,当我尝试访问此控制器时,出现Http 405错误,结果如下:

{"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: 我尝试将以下属性添加到我的GetById()方法中:

[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. 我在网上搜索,并在GitHub页面上找到了关于Api版本的可喜结果 However, I don't understand the suggested fix (using an IActionResult) in this context. 但是,在这种情况下,我不了解建议的修复方法(使用IActionResult)。

Can custom route matching be done while also using versioning? 在使用版本控制的同时可以进行自定义路由匹配吗? If so, how? 如果是这样,怎么办?

You have missed to add api in the route. 您错过了在路线中添加api的操作。 Try it this way 这样尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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