如何更改查询字符串参数的值?

时间:2015-06-18 16:36:32

标签: c# .net-4.5

我有一个像这样的URL的字符串表示:

objectIds

这是一个URL,但在我的代码中是一个字符串对象。如何更改objectIds的值?我是否需要找到字符串&,然后找到之前和之后的{{1}},并用所需的值替换内容?或者有更好的方法吗?

这是一个.NET 4.5 FW控制台应用程序......

2 个答案:

答案 0 :(得分:1)

如果网址的其余部分已修复,您可以手动找到该ID,并使用string.Formatstring.Join将ID插入其中:

var urlString = string.Format(
    "http://www.GoodStuff.xxx/services/stu/query?where=1%3D1&text=&objectIds={0}&time="
,   string.Join("%", ids)
);

这会在您的代码中将%分隔的ids列表插入到网址模板中。

答案 1 :(得分:1)

如果您正在尝试替换已经存在的值,那么它会变得更加棘手。试试这个。

    //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();
    }

它很漂亮,但它可以完成工作。