在C#中,我如何构造和解析嵌套的查询字符串?

Hai*_*ter 1 c# query-string

我正在编写API,并希望人们能够提供Google Charts API调用作为参数.解析这个有问题的API调用的正确方法是什么,其中一个参数包含一个完全独立的API调用?

例如:

?method=createimage&chart1=https://chart.googleapis.com/chart?chs=250x100&chd=t:60,40&cht=p3&chl=Hello|World
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我想把它看作(2)查询字符串键:methodchart1.我是否可以将上面的示例解析为2个查询字符串键,使Google Charts API调用保持原样,而不是将其分解?我可以将这个电话作为JSON或其他内容包围吗?

非常感谢!干杯

Dar*_*rov 6

这是正确的方法(使用ParseQueryString方法):

using System;
using System.Web;

class Program
{
    static void Main()
    {
        var query = "?method=createimage&chart1=https://chart.googleapis.com/chart?chs=250x100&chd=t:60,40&cht=p3&chl=Hello|World";
        var values = HttpUtility.ParseQueryString(query);
        Console.WriteLine(values["method"]);
        Console.WriteLine(values["chart1"]);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想构造这个查询字符串:

using System;
using System.Web;

class Program
{
    static void Main()
    {
        var values = HttpUtility.ParseQueryString(string.Empty);
        values["method"] = "createimage";
        values["chart1"] = "https://chart.googleapis.com/chart?chs=250x100&chd=t:60,40&cht=p3&chl=Hello|World";
        Console.WriteLine(values);
        // prints "method=createimage&chart1=https%3a%2f%2fchart.googleapis.com%2fchart%3fchs%3d250x100%26chd%3dt%3a60%2c40%26cht%3dp3%26chl%3dHello%7cWorld"
    }
}
Run Code Online (Sandbox Code Playgroud)

哦,顺便说一句,你在问题中显示的是一个无效的查询字符串,它由我显示的第二个代码片段的输出确认.您应该对chart1参数进行URL编码.?在查询字符串中包含多个字符绝对违反所有标准.

以下是正确的查询字符串的外观:

?method=createimage&chart1=https%3A%2F%2Fchart.googleapis.com%2Fchart%3Fchs%3D250x100%26chd%3Dt%3A60%2C40%26cht%3Dp3%26chl%3DHello%7CWorld
Run Code Online (Sandbox Code Playgroud)