c# - .NET Core (2.1) Web API Controller 接受请求 url 中的所有内容作为参数

标签 c# .net-core asp.net-core-routing .net-core-2.1

我拥有的是一个 .NET Core 2.1 Web API Controller (在下面的 TestController 中),它应该在接收 GET 请求时生成到其他 url 的重定向。

例子:

Controller 的调用方式如下:http://localhost/api/v1/Test/somedir/somesubdir/filename.extension

它应该返回一个重定向到https://example-domain.com/somedir/somesubdir/filename.extension

这个问题的示例 Controller 如下所示:

  [Authorize]
  [Route("api/v1/[controller]")]
  public class TestController : ControllerBase
  {
    [HttpGet("{path}")]
    public async Task<IActionResult> Get(string path)
    {
      //path e.g. is somedir/somesubdir/filename.extension
      string prefix = "https://example-domain.com/api/v1/Other/";
      //string path2 = HttpContext.Request.Path.Value.Replace("/api/v1/Test/", "/api/v1/Other/").Replace("%2F", "/");
      return Redirect(prefix + path);
    }
  }

我没有让路由正常工作。如果我使用 Swagger 调用该方法,它会被调用(斜杠被 %2F 替换)但至少它会被调用。 如果我通过 postman 调用 Controller ,.NET Core 只会返回 404 Not Found。

我不一定需要 HttpGet("{path}")。我知道我可以获得路径,就像我分配 path2 变量一样。

有什么提示可以使路由正确吗?


另一种可能的解决方案:

正如 John 和 Kirk Larkin 在评论中所指出的,我正在寻找的是一个包罗万象的路由,用“somedir/somesubdir/filename.extension”填充路径参数,独立于之后的路径有多长。

只需在变量名前加一个星号即可。

[HttpGet("{*path}")]

最佳答案

您不需要像您的代码注释所建议的那样考虑 "api/v1/Test",它已被 Controller 级别的 [Route] 属性过滤掉。

对于后面的路径,您可以使用 {*path}:

[HttpGet("{*path}")]
public async Task<IActionResult> Get(string path)
{
    const string prefix = "https://example-domain.com/api/v1/Other/";
    return Redirect(prefix + path);
}

关于c# - .NET Core (2.1) Web API Controller 接受请求 url 中的所有内容作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51615005/

相关文章:

c# - asp.net核心和asp-route-id

c# - 通过 LINQ 中的联结表将表连接在一起

.net - Docker WORKDIR不会创建文件夹

.net-core - 在 Visual Studio 代码中创建类库

razor - 在 Razor 页面 OnPost 模型方法中触发显示模态弹出窗口

c# - 未调用 .NET Core ApiController 方法

c# - 如何为 {id}/visit 创建有效路线?

c# - Datagridview 上下文菜单总是在 hittest 中显示 -1

c# - 在线程中使用 C# 将字符串添加到 WPF 中的列表框

c# - 使用 LINQ 对 ListBox ListItems 进行排序?