【问题标题】:What's the best way to check for duplicate keys in Querystring/Post/Get requests在 Querystring/Post/Get 请求中检查重复键的最佳方法是什么
【发布时间】:2011-09-23 13:07:10
【问题描述】:

我正在编写一个小型 API,需要检查请求中的重复键。有人可以推荐检查重复键的最佳方法。我知道我可以在 key.Value 中检查字符串中的逗号,但是我遇到了另一个问题,即不允许在 API 请求中使用逗号。

    //Does not compile- just for illustration
    private void convertQueryStringToDictionary(HttpContext context)
    {
       queryDict = new Dictionary<string, string>();
        foreach (string key in context.Request.QueryString.Keys)
        {
            if (key.Count() > 0)  //Error here- How do I check for multiple values?
            {       
                context.Response.Write(string.Format("Uh-oh"));
            }
            queryDict.Add(key, context.Request.QueryString[key]);
        }       
    }

【问题讨论】:

    标签: c# query-string


    【解决方案1】:

    QueryString 是一个NameValueCollection,这解释了为什么重复的键值显示为逗号分隔列表(来自Add 方法的文档):

    如果指定的key已经存在于目标NameValueCollection中 例如,将指定的值添加到现有的逗号分隔 “value1,value2,value3”形式的值列表。

    因此,例如,给定这个查询字符串:q1=v1&amp;q2=v2,v2&amp;q3=v3&amp;q1=v4,遍历键并检查值将显示:

    Key: q1  Value:v1,v4 
    Key: q2  Value:v2,v2 
    Key: q3  Value:v3
    

    由于您希望在查询字符串值中允许使用逗号,您可以使用GetValues 方法,该方法将返回一个字符串数组,其中包含查询字符串中键的值。

    static void Main(string[] args)
    {
        HttpRequest request = new HttpRequest("", "http://www.stackoverflow.com", "q1=v1&q2=v2,v2&q3=v3&q1=v4");
    
        var queryString = request.QueryString;
    
        foreach (string k in queryString.Keys)
        {
            Console.WriteLine(k);
            int times = queryString.GetValues(k).Length;
            if (times > 1)
            {
                Console.WriteLine("Key {0} appears {1} times.", k, times);
            }
        }
    
        Console.ReadLine();
    }
    

    向控制台输出以下内容:

    q1
    Key q1 appears 2 times.
    q2
    q3
    

    【讨论】:

    • 我不知道。 +1 并删除了我不准确的答案
    • 哇!非常感谢。你会考虑重写 MSDN 网站吗?
    • 真棒答案@jeff-ogata,有没有办法可以改变这种行为,所以不是这个user_ids[]=1,2,3,我想要这个:user_ids[]=1&amp;user_ids[]=2&amp;user_ids[]=3
    猜你喜欢
    • 2010-11-25
    • 1970-01-01
    • 2020-04-24
    • 2015-08-06
    • 2014-01-30
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 2011-06-21
    相关资源
    最近更新 更多