【问题标题】:Why is HttpRequestMessage decoding my encoded string为什么 HttpRequestMessage 解码我的编码字符串
【发布时间】:2021-08-04 12:27:29
【问题描述】:

我正在尝试发出Http 请求,如下所示:

var category = Uri.EscapeDataString("Power Tools");

var request = new HttpRequestMessage(HttpMethod.Get, $"/api/Items/GetAll?category={category}");

category 现在等于:Power%20Tools

请求被翻译成:

request = {Method: GET, RequestUri: 'http://localhost/api/Items/GetAll?category=Power Tools', ...

为什么HttpRequestMessage 解码我的编码字符串?

【问题讨论】:

  • 您在哪里阅读请求?
  • @vernou 我正在调试该方法。我只是悬停在它上面。我在控制器上有一个正则表达式验证输入。它不接受空格。
  • 我认为您需要包含更多细节。我刚刚做了一个快速测试,但没有看到相同的行为。
  • @vernou 我看到了http://localhost/api/Items/GetAll?category=Power%20Tools。但是,控制器看到Power Tools 并以错误消息响应。我的正则表达式是^[a-zA-Z0-9%]+$。如果我在正则表达式中添加一个空格,这将有效。
  • 更清楚一点:Category 的值是“Power Tools”,但是为了在 URL 中清楚地表示它,我们必须对其进行转义(因此它变成了“Power%20Tools”)。因为转义只是使 URL 起作用,所以当 ASP.NET 将它传递给控制器​​方法时,它会被解码。

标签: c# httprequest


【解决方案1】:

我在 .NET 5 的控制台应用程序中重现。我认为,只是 ToString 将 url 解码为对调试信息友好。我在文档中没有找到这方面的信息,但 .NET 现在是开源的。

一般情况下,ToString 方法用于生成调试信息。看 见HttpRequestMessage.ToString的源码:

public override string ToString()
{
    StringBuilder sb = new StringBuilder();

    sb.Append("Method: ");
    sb.Append(method);

    sb.Append(", RequestUri: '");
    sb.Append(requestUri == null ? "<null>" : requestUri.ToString());
    ...
    return sb.ToString();
}

这只是显示requsetUri.ToString()requestUriUri 的类型。 来自Uri.String的官方文档:

Uri 实例的未转义规范表示。除 #、? 和 % 外,所有字符均未转义。

// Create a new Uri from a string address.
Uri uriAddress = new Uri("HTTP://www.Contoso.com:80/thick%20and%20thin.htm");

// Write the new Uri to the console and note the difference in the two values.
// ToString() gives the canonical version.  OriginalString gives the orginal
// string that was passed to the constructor.

// The following outputs "http://www.contoso.com/thick and thin.htm".
Console.WriteLine(uriAddress.ToString());

// The following outputs "HTTP://www.Contoso.com:80/thick%20and%20thin.htm".
Console.WriteLine(uriAddress.OriginalString);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多