如何从 URL 编码中获取参数?
How to get a parameter from a URL encoded?
我有以下代码从 URL 获取参数及其密钥:
string queryString = new Uri(URL).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
var paramsList = new Dictionary<string, string>();
foreach (var parameter in queryDictionary)
{
var key = (string)parameter;
var value = System.Web.HttpUtility.ParseQueryString(queryString).Get(key);
}
效果很好。例外,在 value
中,我有 decoded value
。在解码之前,我需要在地址中保留它。我该怎么做?请注意,在某些情况下给出不同的值后对其进行编码。
一种可行的方法是将其编码回来:
var encodedValue = HttpUtility.UrlEncode(value);
当您访问查询字符串时,ASP.NET 会自动调用 HttpUtility.UrlDecode。
这有点脏,但应该可以正常工作。
编码已经在您的第一行进行:
string queryString = new Uri(URL).Query;
您可能想避免编写自己的代码来从 URL 中提取查询部分。这是明智的。您仍然可以依靠 Uri
class 为您进行解析:
var uri=new Uri(URL);
var queryString= URL.Replace(uri.GetLeftPart(UriPartial.Path), "").TrimStart('?');
——————————————————————————————————
(
var URL="http://a/b/?d= @£$%% sdf we 456 7 5?367";
var uri=new Uri(URL);
Console.WriteLine(uri.Query); // Already url-encoded by the Uri constructor
var queryString = URL.Replace(uri.GetLeftPart(UriPartial.Path), "").TrimStart('?');
Console.WriteLine(System.Web.HttpUtility.ParseQueryString(queryString)); //Not encoded!
)
(顺便说一句,LinqPad 有帮助)
我有以下代码从 URL 获取参数及其密钥:
string queryString = new Uri(URL).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
var paramsList = new Dictionary<string, string>();
foreach (var parameter in queryDictionary)
{
var key = (string)parameter;
var value = System.Web.HttpUtility.ParseQueryString(queryString).Get(key);
}
效果很好。例外,在 value
中,我有 decoded value
。在解码之前,我需要在地址中保留它。我该怎么做?请注意,在某些情况下给出不同的值后对其进行编码。
一种可行的方法是将其编码回来:
var encodedValue = HttpUtility.UrlEncode(value);
当您访问查询字符串时,ASP.NET 会自动调用 HttpUtility.UrlDecode。
这有点脏,但应该可以正常工作。
编码已经在您的第一行进行:
string queryString = new Uri(URL).Query;
您可能想避免编写自己的代码来从 URL 中提取查询部分。这是明智的。您仍然可以依靠 Uri
class 为您进行解析:
var uri=new Uri(URL);
var queryString= URL.Replace(uri.GetLeftPart(UriPartial.Path), "").TrimStart('?');
——————————————————————————————————
(
var URL="http://a/b/?d= @£$%% sdf we 456 7 5?367";
var uri=new Uri(URL);
Console.WriteLine(uri.Query); // Already url-encoded by the Uri constructor
var queryString = URL.Replace(uri.GetLeftPart(UriPartial.Path), "").TrimStart('?');
Console.WriteLine(System.Web.HttpUtility.ParseQueryString(queryString)); //Not encoded!
)
(顺便说一句,LinqPad 有帮助)