如何在System.Net.WebUtility.UrlEncode中强制使用%20而不是+
本文关键字:System Net WebUtility UrlEncode | 更新日期: 2023-09-27 18:12:02
我需要在不想引用System.Web的类库程序集中编码URL。URL包含多个空格
https://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quote where symbol in ("YHOO","AAPL")&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=
当我使用System.Net.WebUtility.UrlEncode()时,空格被替换为"+",这不起作用。我需要用%20
来替换它们如何在不引用System.Web的情况下实现这一点?
您可以尝试System
程序集中的Uri.EscapeUriString
,它会转义URI字符串。对于问题中的字符串,它返回:
https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20%20symbol%20in%20(%22YHOO%22,%22AAPL%22)&format=json&diagnostics=true&env=store%253A%252F%252Fdatatables.org%252Falltableswithkeys&callback=
Uri.EscapeDataString()
更适合您的目的,因为Uri.EscapeUriString()
可以跳过一些特殊字符
HttpUtility。ParseQueryString将工作,只要你是在一个web应用程序,或者不介意包括对System.Web的依赖。另一种方法是:
NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
string[] parts = segment.Split('=');
if (parts.Length > 0)
{
string key = parts[0].Trim(new char[] { '?', ' ' });
string val = parts[1].Trim();
queryParameters.Add(key, val);
}
}