简体   繁体   English

c#如何检查QueryString Values count是否与key的数量具有相同的值

[英]c# how to check if QueryString Values count has the same value as count of keys

Here is my problem: 这是我的问题:

If my url has QueryString ?asdasdafa I can handle it with : if(HttpContext.Current.Request.QueryString.HasKeys()) 如果我的url有QueryString ?asdasdafa我可以用: if(HttpContext.Current.Request.QueryString.HasKeys())来处理它

But if my url has QueryString ?asdasasfasdas&brand=Sony then it will fail with null exception because is actually has one key, and the other one doesn't have it. 但是如果我的url有QueryString ?asdasasfasdas&brand=Sony那么它会因为null异常而失败,因为它实际上只有一个键,而另一个没有它。 Is there an easy way to check 有一个简单的方法来检查

if(HttpContext.Current.Request.QueryString.KeysCount ==
HttpContext.Current.Request.QuesryString.ValuesCount))

I don't think you need to do that, doing a simple null check will suffice 我认为你不需要这样做,做一个简单的空检查就足够了

if(Request.QueryString["asdasdafa"]==null)
{
   // value missing
}

The fact that asdasdafa is not even included as one of the keys on the QueryString won't make your application throw an Exception. 事实上, asdasdafa甚至不包含在QueryString中的一个键上,这不会使您的应用程序抛出异常。

EDIT 编辑

Based on the comment, you could then walk through the keys present as so: 根据评论,您可以按照以下方式浏览当前的键:

foreach (var item in Request.QueryString.AllKeys)
{
   if (Request.QueryString[item] == null)
                //value missing

}

When I run your 2nd example, HttpContext.Current.Request.QueryString.HasKeys() doesn't fail for me, and asdasasfasdas is the first value I get, but its key is null . 当我运行你的第二个例子时, HttpContext.Current.Request.QueryString.HasKeys()对我来说不会失败, asdasasfasdas是我得到的第一个值,但它的键是null You can check if the key is null by 您可以检查密钥是否为空

NameValueCollection nvc = Context.Request.QueryString;
if (nvc.GetKey(0) == null){}

I am not sure whether HasKeys can handle that, If not,how about writing your own extension method / override the HasKeys() ?. 我不确定HasKeys是否可以处理它,如果没有,如何编写自己的扩展方法/覆盖HasKeys()? Read the querystring in that method and split it with & and then again with = on each items of the first split result. 读取该方法中的查询字符串并使用&拆分它,然后在第一个拆分结果的每个项目上再次使用=。 Then return Yes or No 然后返回是或否

I haven't tested this so I don't know if it works, but you could try checking against these counts: 我没有测试过这个,所以我不知道它是否有效,但你可以尝试检查这些计数:

int keys = Request.QueryString.Keys.Count;
int args = Request.QueryString.Count;

if (keys != args) ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM