c# – 在QuerystringPostGet请求中检查重复键的最佳方法是什么?

c# – 在QuerystringPostGet请求中检查重复键的最佳方法是什么?,第1张

概述我正在编写一个小型API,需要在请求检查重复的密钥.有人可以推荐检查重复键的最佳方法.我知道我可以检查key.Value在字符串中的逗号,但是我有另一个问题,不允许在API请求中使用逗号. //Does not compile- just for illustration private void convertQueryStringToDictionary(HttpContext co 我正在编写一个小型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]);        }           }
解决方法 queryString是一个nameValueCollection,它解释了为什么重复键值显示为逗号分隔列表(从 Add方法的文档):

If the specifIEd key already exists in the target nameValueCollection
instance,the specifIEd value is added to the existing comma-separated
List of values in the form “value1,value2,value3”.

所以,例如,给定这个查询字符串:q1 = v1& q2 = v2,v2& q3 = v3& 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();}

将以下内容输出到控制台:

q1Key q1 appears 2 times.q2q3
总结

以上是内存溢出为你收集整理的c# – 在Querystring / Post / Get请求中检查重复键的最佳方法是什么?全部内容,希望文章能够帮你解决c# – 在Querystring / Post / Get请求中检查重复键的最佳方法是什么?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1240128.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存