如何更改查询字符串参数的值
本文关键字:参数 字符串 何更改 查询 | 更新日期: 2023-09-27 17:57:10
>我有一个URL的字符串表示形式,如下所示:
http://www.GoodStuff.xxx/services/stu/query?where=1%3D1&text=&objectIds=231699%2C232002%2C231700%2C100646&time=
它是一个 URL,但在我的代码中是一个字符串对象。如何更改objectIds
的值?我是否需要找到字符串,objectIds
,然后找到前后的&
,并将内容替换为所需的值?还是有更好的方法?
这是一个 .NET 4.5 固件控制台应用...
如果 URL 的其余部分是固定的,您可以手动找到 id,并使用 string.Format
和 string.Join
将 ID 插入其中:
var urlString = string.Format(
"http://www.GoodStuff.xxx/services/stu/query?where=1%3D1&text=&objectIds={0}&time="
, string.Join("%", ids)
);
这会将代码中以%
分隔的ids
列表插入到 URL 模板中。
如果您尝试替换已经存在的值,它会变得更加棘手。试试这个。
//Base URL. Doesn't need to be hardcoded. As long as it contains "objectIds=" then it will work
static string url = @"http://www.GoodStuff.xxx/services/stu/query?where=1%3D1&text=&objectIds=231699%2C232002%2C231700%2C100646&time=";
static void Main(string[] args)
{
//Get the start index
// +10 because IndexOf gets us to the o but we want the index of the equal sign
int startIndex = url.IndexOf("objectIds=") + 10;
//Figure out how many characters we are skipping over.
//This is nice because then it doesn't matter if the value of objectids is 0 or 99999999
int endIndex = url.Substring(startIndex).IndexOf('&');
//Cache the second half of the URL
String secondHalfOfURL = url.Substring(startIndex + endIndex);
//Our new IDs to stick in
int newObjectIDs = 12345;
//The new URL.
//First, we get the string up to the equal sign of the objectIds value
//Next we put our IDS in.
//Finally we add on the second half of the URL
String NewURL = url.Substring(0, startIndex) + newObjectIDs + secondHalfOfURL;
Console.WriteLine(NewURL);
Console.Read();
}
它不漂亮,但它可以完成工作。