Answers:
使用返回ParseQueryString
的System.Web.HttpUtility
类的静态方法NameValueCollection
。
Uri myUri = new Uri("http://www.example.com?param1=good¶m2=bad");
string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("param1");
HttpUtility.ParseQueryString(myUri.Query).Get(0)
,它将提取第一个参数。`
HttpUtility.ParseQueryString(string)
!解析完整的查询URL 。顾名思义,它是解析查询字符串,而不是带有查询参数的URL。如果要执行此操作,则必须首先按?
如下方式将其拆分:Url.Split('?')
并使用[0]
LINQ的Last()
/ 来获取最后一个元素(取决于情况和所需)LastOrDefault()
。
这可能是您想要的
var uri = new Uri("http://domain.test/Default.aspx?var1=true&var2=test&var3=3");
var query = HttpUtility.ParseQueryString(uri.Query);
var var2 = query.Get("var2");
如果出于某种原因您不愿意使用,这是另一种选择HttpUtility.ParseQueryString()
。
构造它可以容忍“格式错误”的查询字符串,即http://test/test.html?empty=
成为具有空值的参数。如果需要,调用者可以验证参数。
public static class UriHelper
{
public static Dictionary<string, string> DecodeQueryParameters(this Uri uri)
{
if (uri == null)
throw new ArgumentNullException("uri");
if (uri.Query.Length == 0)
return new Dictionary<string, string>();
return uri.Query.TrimStart('?')
.Split(new[] { '&', ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(parameter => parameter.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
.GroupBy(parts => parts[0],
parts => parts.Length > 2 ? string.Join("=", parts, 1, parts.Length - 1) : (parts.Length > 1 ? parts[1] : ""))
.ToDictionary(grouping => grouping.Key,
grouping => string.Join(",", grouping));
}
}
测试
[TestClass]
public class UriHelperTest
{
[TestMethod]
public void DecodeQueryParameters()
{
DecodeQueryParametersTest("http://test/test.html", new Dictionary<string, string>());
DecodeQueryParametersTest("http://test/test.html?", new Dictionary<string, string>());
DecodeQueryParametersTest("http://test/test.html?key=bla/blub.xml", new Dictionary<string, string> { { "key", "bla/blub.xml" } });
DecodeQueryParametersTest("http://test/test.html?eins=1&zwei=2", new Dictionary<string, string> { { "eins", "1" }, { "zwei", "2" } });
DecodeQueryParametersTest("http://test/test.html?empty", new Dictionary<string, string> { { "empty", "" } });
DecodeQueryParametersTest("http://test/test.html?empty=", new Dictionary<string, string> { { "empty", "" } });
DecodeQueryParametersTest("http://test/test.html?key=1&", new Dictionary<string, string> { { "key", "1" } });
DecodeQueryParametersTest("http://test/test.html?key=value?&b=c", new Dictionary<string, string> { { "key", "value?" }, { "b", "c" } });
DecodeQueryParametersTest("http://test/test.html?key=value=what", new Dictionary<string, string> { { "key", "value=what" } });
DecodeQueryParametersTest("http://www.google.com/search?q=energy+edge&rls=com.microsoft:en-au&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1%22",
new Dictionary<string, string>
{
{ "q", "energy+edge" },
{ "rls", "com.microsoft:en-au" },
{ "ie", "UTF-8" },
{ "oe", "UTF-8" },
{ "startIndex", "" },
{ "startPage", "1%22" },
});
DecodeQueryParametersTest("http://test/test.html?key=value;key=anotherValue", new Dictionary<string, string> { { "key", "value,anotherValue" } });
}
private static void DecodeQueryParametersTest(string uri, Dictionary<string, string> expected)
{
Dictionary<string, string> parameters = new Uri(uri).DecodeQueryParameters();
Assert.AreEqual(expected.Count, parameters.Count, "Wrong parameter count. Uri: {0}", uri);
foreach (var key in expected.Keys)
{
Assert.IsTrue(parameters.ContainsKey(key), "Missing parameter key {0}. Uri: {1}", key, uri);
Assert.AreEqual(expected[key], parameters[key], "Wrong parameter value for {0}. Uri: {1}", parameters[key], uri);
}
}
}
@Andrew和@CZFox
我有同样的错误,发现原因实际上是一个参数:http://www.example.com?param1
而不是param1
是一个期望的参数。
通过删除问号之前和包括的所有字符,可以解决此问题。因此,从本质上讲,该HttpUtility.ParseQueryString
函数仅需要一个有效的查询字符串参数,该参数仅在问号后包含字符,如下所示:
HttpUtility.ParseQueryString ( "param1=good¶m2=bad" )
我的解决方法:
string RawUrl = "http://www.example.com?param1=good¶m2=bad";
int index = RawUrl.IndexOf ( "?" );
if ( index > 0 )
RawUrl = RawUrl.Substring ( index ).Remove ( 0, 1 );
Uri myUri = new Uri( RawUrl, UriKind.RelativeOrAbsolute);
string param1 = HttpUtility.ParseQueryString( myUri.Query ).Get( "param1" );`
ParseQueryString
解析查询字符串。
看起来您应该循环遍历的值myUri.Query
并从那里解析它。
string desiredValue;
foreach(string item in myUri.Query.Split('&'))
{
string[] parts = item.Replace("?", "").Split('=');
if(parts[0] == "desiredKey")
{
desiredValue = parts[1];
break;
}
}
但是,如果不对一堆格式错误的URL进行测试,我将不会使用此代码。它可能会中断以下所有/全部:
hello.html?
hello.html?valuelesskey
hello.html?key=value=hi
hello.html?hi=value?&b=c
或者,如果您不知道网址(为避免硬编码,请使用 AbsoluteUri
例子...
//get the full URL
Uri myUri = new Uri(Request.Url.AbsoluteUri);
//get any parameters
string strStatus = HttpUtility.ParseQueryString(myUri.Query).Get("status");
string strMsg = HttpUtility.ParseQueryString(myUri.Query).Get("message");
switch (strStatus.ToUpper())
{
case "OK":
webMessageBox.Show("EMAILS SENT!");
break;
case "ER":
webMessageBox.Show("EMAILS SENT, BUT ... " + strMsg);
break;
}