【问题标题】:Handing Get/{id} vs Get/id with flurl使用 Flurl 处理 Get/{id} 与 Get/id
【发布时间】:2017-08-02 12:44:34
【问题描述】:

我正在尝试让Flurl 工作,但在传递 ID 时我不知道如何工作。

[HttpGet("Get/{id}")]
public IActionResult Get(int id)
{
    // Some something and return
}

以上预期

Get/1

所以在 Flurl 中:

var result = await _baseUrl
    .AppendPathSegment("/Get")
    .SetQueryParam("id", id)
    .GetJsonAsync();

这会产生这个:

/Get?id=8

...然后以 404 失败。

如何让 Flurl 设置查询参数 /id 或让我的 get 同时接受 Get/id 和 Get?id=

我可以做以下,但看起来不是很优雅

var result = await _baseUrl
    .AppendPathSegment(string.Format("/Get/{0}", id))
    .GetJsonAsync();

【问题讨论】:

  • 我没用过 Flurl,但我猜SetQueryParam 会设置一个查询字符串,但你正在构建一个路径。可以_baseUrl.AppendPathSegments("get", id.ToString())吗?
  • @DavidG 我可以,不需要 .ToString。那很简单!添加一个答案,我会接受。谢谢

标签: c# get asp.net-core-mvc flurl


【解决方案1】:

SetQueryParam 会将值添加为查询字符串,但您需要将该值作为路径的一部分。而是考虑使用AppendPathSegments 方法,例如:

var result = _baseUrl
    .AppendPathSegments("get", id)
    .GetJsonAsync();

【讨论】:

    【解决方案2】:

    我是这样使用的:

    var result = "https://api.site.com/v1/".AppendPathSegment("endpoint").AppendPathSeparator().SetQueryParam("get", id)
    // Outputs: "https://api.site.com/v1/endpoint/?get=5"
    

    【讨论】:

    • OP 特别不想要查询字符串。
    猜你喜欢
    • 2015-11-06
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多