.NET Core (2.1) Web API 控制器接受请求 url 中的所有内容作为参数 [英] .NET Core (2.1) web API controller accepting all that follows within the request url as parameter

查看:46
本文介绍了.NET Core (2.1) Web API 控制器接受请求 url 中的所有内容作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What I have is a .NET Core 2.1 web API controller (in the following the TestController) that should generate redirects to other urls when receiving GET requests.

示例:

控制器调用如下:http://localhost/api/v1/Test/somedir/somesubdir/filename.extension

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

and it should return a redirect to https://example-domain.com/somedir/somesubdir/filename.extension

我针对这个问题的示例控制器如下所示:

My example controller for this question looks like:

  [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 替换),但至少它会被调用.如果我通过邮递员 .NET Core 调用控制器,只会返回 404 Not Found.

I don't get the routing to work. If I call the method with Swagger it get's called (with the slashes replaced by %2F) but at least it gets called. If I call the controller via postman .NET Core just returns 404 Not Found.

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

I do not necessarily need the HttpGet("{path}"). I know that I could get the path like I assigned the path2 variable.

任何提示我如何才能正确路由?

Any hints how I could get the routing right?

另一种可能的解决方案:

Another possible solution:

正如 John 和 Kirk Larkin 在评论中所指出的,我正在寻找的是一个包罗万象的路由,用somedir/somesubdir/filename.extension"填充路径参数,与之后的路径长度无关.

As pointed out by John and Kirk Larkin in the comments what I was looking for is a catch-all route filling the path argument with "somedir/somesubdir/filename.extension" independent how long the path afterwards is.

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

Just an asterisk in front of the variable name does the trick.

[HttpGet("{*path}")]

[HttpGet("{*path}")]

推荐答案

你不需要把 "api/v1/Test" 考虑在内,正如你的代码注释所建议的,它已经被过滤了通过控制器级别的 [Route] 属性输出.

You don't need to take "api/v1/Test" into account as your code comments suggest, it is already filtered out by the [Route] attribute on the Controller level.

对于接下来的路径,您可以使用{*path}:

For the rest of the path that follows you can use {*path}:

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

这篇关于.NET Core (2.1) Web API 控制器接受请求 url 中的所有内容作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆