【问题标题】:How to correctly receive string in url format in ASP NET Core 3.1?如何在 ASP NET Core 3.1 中正确接收 url 格式的字符串?
【发布时间】:2021-01-05 22:19:04
【问题描述】:

假设我们有一个 API,它在其控制器操作之一中接收 URL。这在 Net Core 3.1 中如何实现?如果我理解正确,那么https://www.test.com/anothertest/test 会搞乱到控制器的路由吗?

下面的代码示例

[Route("api/[controller]")]
public class TestController : Controller
{
    [HttpPost("{url}")]
    public ActionResult<string> Post(string url)
    {
        // I want this to work! The url should be the full url specified i.e. https://www.myawesome.com/url/with/slashes
    }
}

所以如果我调用 https://localhost:5001/api/Test/https://www.url.com/with/slashes 我会得到 https://www.url.com/with/slashes 作为传入的 url 参数。

【问题讨论】:

  • 嗨@Tomato,你想获取url字符串吗?

标签: c# api asp.net-core controller asp.net-core-3.1


【解决方案1】:

如果您将https://www.url.com/with/slashes 作为网址的一部分传递,“/”将无法识别。

通常,传递 url 最简单的方法是通过查询字符串。

您可以像下面这样更改您的代码。

    [HttpPost]
    public ActionResult<string> Post(string url)
    {
        //...
    }

那么url应该是

https://localhost:xxxxx/api/test/?url=https://www.url.com/with/slashes

【讨论】:

  • 嗯,这就是我想避免的 :(。一个小的修复是 URL 将是 https://localhost:xxxxx/api/test?url=https://www.url.com/with/slashes
猜你喜欢
  • 2019-06-30
  • 2022-02-19
  • 1970-01-01
  • 2021-07-17
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 2020-08-20
相关资源
最近更新 更多