c# - 将值附加到查询字符串

标签 c# parameters query-string

我有一组类似于下面列表中的 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
}

但是它只返回像这样的参数 idserverlocation 等基于提供的 URL。

我需要的是向现有查询字符串添加/附加值。

例如 URL:

http://somesite.example/backup/index.php?action=login&attempts=1

我需要更改查询字符串参数的值:

action=login1

attempts=11

如您所见,我为每个值附加了“1”。我需要从一个字符串中获取一组 URL,其中包含不同的查询字符串,并在末尾为每个参数添加一个值,然后再次将它们添加到列表中。

最佳答案

您可以使用 HttpUtility.ParseQueryString方法和 UriBuilder它提供了一种很好的方式来处理查询字符串参数,而无需担心解析、URL 编码等问题......:

string longurl = "http://somesite.example/news.php?article=1&lang=en";
var uriBuilder = new UriBuilder(longurl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query["action"] = "login1";
query["attempts"] = "11";
uriBuilder.Query = query.ToString();
longurl = uriBuilder.ToString();
// "http://somesite.example:80/news.php?article=1&lang=en&action=login1&attempts=11"

关于c# - 将值附加到查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14517798/

相关文章:

c# - 在 WinForms C# 上撕裂我的动画

c# - 为什么纯 IEnumerable 的内容对于 WPF DataGrid 是不可见的?

c++ - 模板函数和 Const/NonConst 引用参数

arrays - VB.NET数组参数机制,byval和byref

http - 带有 a/in 的查询字符串有效吗?

java - Lagom -如何将带有查询参数(数组类型)的端点映射到restcall

c# - 单击按钮时记录删除的文件?记录所有文件(已删除和未删除)

c# - 属性 'Text' 上的 ContentPropertyAttribute 无效

python - Python 中的参数和参数如何工作?

java - 如何从 URL 中提取参数,无论其书写方式如何?