【问题标题】:Using custom route with versioning in ASP.NET Core 2.0在 ASP.NET Core 2.0 中使用带有版本控制的自定义路由
【发布时间】:2018-04-03 14:54:48
【问题描述】:

我使用自定义中间件将请求中使用的路径更改为 WebApi。

在我的中间件调用中,我有:

// 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);

在我的 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...
  }
}

但是,当我尝试访问此控制器时,我收到一个 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}}

我尝试将以下属性添加到我的 GetById() 方法中:

[MapToApiVersion("1.0")]

但这并没有帮助。

我在网上搜索并在 GitHub 页面上找到了一个 promising result 用于版本控制 Api。但是,在这种情况下,我不理解建议的修复(使用 IActionResult)。

是否可以在使用版本控制的同时进行自定义路由匹配?如果有,怎么做?

【问题讨论】:

    标签: c# rest asp.net-web-api


    【解决方案1】:

    您错过了在路由中添加 api。试试这个方法

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

    【讨论】:

    • 这样一个简单的遗漏让我花了大约一个小时的麻烦。总是小事。感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 2019-05-27
    • 2020-10-03
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多