C# 从.NET中的字符串获取URL参数
我在.NET中有一个字符串,它实际上是一个URL。我想用一种简单的方法从一个特定的参数中获取值C# 从.NET中的字符串获取URL参数,c#,.net,url,parsing,parameters,C#,.net,Url,Parsing,Parameters,我在.NET中有一个字符串,它实际上是一个URL。我想用一种简单的方法从一个特定的参数中获取值 Uri myUri = new Uri("http://www.example.com?param1=good¶m2=bad"); var params = myUri.ParseQueryString(); var specific = myUri.ParseQueryString().Get("spesific"); var paramByI
Uri myUri = new Uri("http://www.example.com?param1=good¶m2=bad");
var params = myUri.ParseQueryString();
var specific = myUri.ParseQueryString().Get("spesific");
var paramByIndex = = myUri.ParseQueryString().Get(1);
通常,我只会使用Request.Params[“thingiwant”]
,但这个字符串不是来自请求。我可以创建一个新的Uri
项,如下所示:
Uri myUri = new Uri(TheStringUrlIWantMyValueFrom);
我可以使用myUri.Query
来获取查询字符串……但显然我必须找到一些正则表达式来拆分它
我是否遗漏了一些明显的东西,或者除了创建某种regex之外,没有内置的方法来完成这项工作,等等?看起来您应该循环使用
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
- 等
使用返回NameValueCollection
的System.Web.HttpUtility
类的静态ParseQueryString
方法
Uri myUri = new Uri("http://www.example.com?param1=good¶m2=bad");
string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("param1");
查看System.Web.HttpValueCollection
的FillFromString
方法中的文档。这将为您提供ASP.NET用于填充请求.QueryString
集合的代码。这可能就是您想要的
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");
@安德鲁和福克斯
我也有同样的错误,并发现原因是参数1实际上是: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" );`
您也可以使用以下变通方法来处理第一个参数:
var param1 =
HttpUtility.ParseQueryString(url.Substring(
new []{0, url.IndexOf('?')}.Max()
)).Get("param1");
如果出于任何原因,您不能或不想使用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));
}
}
公共静态类
{
公共静态字典DecodeQueryParameters(此Uri)
{
if(uri==null)
抛出新的ArgumentNullException(“uri”);
if(uri.Query.Length==0)
返回新字典();
返回uri.Query.TrimStart(“?”)
.Split(新[]{'&',';'},StringSplitOptions.RemoveEmptyEntries)
.Select(parameter=>parameter.Split(新[]{'=},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(“,”分组));
}
}
测试
[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);
}
}
}
[TestClass]
公共类UriHelperTest
{
[测试方法]
public void DecodeQueryParameters()
{
DecodeQueryParametersTest(“http://test/test.html“,新字典());
DecodeQueryParametersTest(“http://test/test.html?“,新字典());
DecodeQueryParametersTest(“http://test/test.html?key=bla/blub.xml,新字典{{“key”,“bla/blub.xml});
DecodeQueryParametersTest(“http://test/test.html?eins=1&zwei=2新词典{{“eins”、“1”}、{“zwei”、“2”});
DecodeQueryParametersTest(“http://test/test.html?empty,新字典{{“empty”,新字典{});
DecodeQueryParametersTest(“http://test/test.html?empty=,新字典{{“empty”,新字典{});
DecodeQueryParametersTest(“http://test/test.html?key=1&新字典{{“key”,“1}});
DecodeQueryParametersTest(“http://test/test.html?key=value?&b=c,新字典{{“key”,“value?”},{“b”,“c”});
DecodeQueryParametersTest(“http://test/test.html?key=value=what,新字典{{“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“,
新词典
{
{“q”,“能量+边缘”},
{“rls”,“com.microsoft:en-au”},
{“ie”,“UTF-8”},
{“oe”,“UTF-8”},
{“startIndex”,“”},
{“起始页”,“1%22”},
});
DecodeQueryParametersTest(“http://test/test.html?key=value;key=anotherValue”,新字典{{“key”,“value,anotherValue”});
}
私有静态void DecodeQueryParametersTest(字符串uri,需要字典)
{
字典参数=新Uri(Uri).DecodeQueryParameters();
AreEqual(应为.Count,parameters.Count,“错误的参数计数.Uri:{0}”,Uri);
foreach(应为.Keys中的var键)
{
IsTrue(parameters.ContainsKey(key),“缺少参数key{0}.Uri:{1}”,key,Uri);
AreEqual(应为[key],参数[key],“错误的{0}.Uri:{1}”参数值,参数[key],Uri);
}
}
}
如果您想在默认页面上获取查询字符串。默认页面表示您当前的页面url。
您可以尝试以下代码:
string paramIl = HttpUtility.ParseQueryString(this.ClientQueryString).Get("city");
或者,如果您不知道URL(为了避免硬编码,请使用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;
}
我用了它,它运行得很好
<%=Request.QueryString["id"] %>
这其实很简单,对我来说很有效:)
对于希望循环遍历字符串中所有查询字符串的任何人
foreach (var item in new Uri(urlString).Query.TrimStart('?').Split('&'))
{
var subStrings = item.Split('=');
var key = subStrings[0];
var value = subStrings[1];
// do something with values
}
单线LINQ解决方案:
Dictionary<string, string> ParseQueryString(string query)
{
return query.Replace("?", "").Split('&').ToDictionary(pair => pair.Split('=').First(), pair => pair.Split('=').Last());
}
字典解析
Dictionary<string, string> ParseQueryString(string query)
{
return query.Replace("?", "").Split('&').ToDictionary(pair => pair.Split('=').First(), pair => pair.Split('=').Last());
}
Uri myUri = new Uri("http://www.example.com?param1=good¶m2=bad");
var params = myUri.ParseQueryString();
var specific = myUri.ParseQueryString().Get("spesific");
var paramByIndex = = myUri.ParseQueryString().Get(1);