我有一组类似于下面列表中的url
http://somesite.example/backup/lol.php?id=1&server=4&location=us
http://somesite.example/news.php?article=1&lang=en
我已经设法获得查询字符串使用以下代码:
myurl = longurl.Split('?');
NameValueCollection qs = HttpUtility.ParseQueryString(myurl [1]);
foreach (string lol in qs)
{
// results will return
}
但它只返回参数
id、服务器、位置等等,基于所提供的URL。
我需要的是向现有的查询字符串添加/追加值。
例如,使用URL:
http://somesite.example/backup/index.php?action=login&attempts=1
我需要改变查询字符串参数的值:
操作 = 登录 1
尝试= 11
如您所见,我为每个值附加了“1”。我需要从一个字符串中获得一组url,其中包含不同的查询字符串,并在末尾为每个参数添加一个值&再次将它们添加到列表中。
下面的解决方案适用于ASP。NET 5 (vNext),它使用QueryHelpers类来构建带有参数的URI。
public Uri GetUri()
{
var location = _config.Get("http://iberia.com");
Dictionary<string, string> values = GetDictionaryParameters();
var uri = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(location, values);
return new Uri(uri);
}
private Dictionary<string,string> GetDictionaryParameters()
{
Dictionary<string, string> values = new Dictionary<string, string>
{
{ "param1", "value1" },
{ "param2", "value2"},
{ "param3", "value3"}
};
return values;
}
结果URI应该是http://iberia.com?param1=value1¶m2=value2¶m3=value3
下面的解决方案适用于ASP。NET 5 (vNext),它使用QueryHelpers类来构建带有参数的URI。
public Uri GetUri()
{
var location = _config.Get("http://iberia.com");
Dictionary<string, string> values = GetDictionaryParameters();
var uri = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(location, values);
return new Uri(uri);
}
private Dictionary<string,string> GetDictionaryParameters()
{
Dictionary<string, string> values = new Dictionary<string, string>
{
{ "param1", "value1" },
{ "param2", "value2"},
{ "param3", "value3"}
};
return values;
}
结果URI应该是http://iberia.com?param1=value1¶m2=value2¶m3=value3
注意,你可以添加微软的Microsoft. aspnetcore . webutilities nuget包,然后用它来附加值到查询字符串:
QueryHelpers.AddQueryString(longurl, "action", "login1")
QueryHelpers.AddQueryString(longurl, new Dictionary<string, string> { { "action", "login1" }, { "attempts", "11" } });