首页 > 解决方案 > 为什么 HttpRequestMessage 解码我的编码字符串

问题描述

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

标签: c#httprequest

解决方案


我在 .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);

推荐阅读