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

Why is HttpRequestMessage decoding my encoded string

我正在尝试发出 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 解码我的编码字符串?

我在 .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的官方文档:

The unescaped canonical representation of the Uri instance. All characters are unescaped except #, ?, and %.

// 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);