c# - 为什么 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
解码我的编码字符串?
解决方案
我在 .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()
并且requestUri
是Uri
. 来自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);
推荐阅读
- python - 不确定如何在连接数据库的情况下更新 python 中的组合框
- bitrise - 无法在 bitrise 上部署 Play 商店,出现错误 400:收到无效的 JSON 有效负载
- vb.net - 使用 OpenFileDialogbox 加载新的 excel 或访问文件到 datagridview
- python-3.x - Bs4 找不到正确的元素
- python - re.compile("[" ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-7: truncated \UXXXXXXXX escape
- android-studio - Android SDK 工具(已过时)
- java - Apache Camel - 处理 404 错误的最佳方法是什么?
- cordova - 如何使用 Cordova 打印机插件打印组件 div
- linux - ARM ORR寄存器的区别
- ruby-on-rails - HEROKU 和 Ruby on rails:问题数据库