English 中文(简体)
空的 QueryString 参数
原标题:
  • 时间:2008-12-30 14:20:28
  •  标签:

The Problem

使用ASP.NET,检查以下url查询字符串中的foo参数的正确方法是什么? 这是否可能?

http://example.com?bar=3&foo

我已经尝试检查Request ["foo"] 以及Request.QueryString ["foo"] ,但两者都得到null。 我还尝试使用 QueryString 集合中的值填充一个 List ,但正如我在下面提到的那样,它不包括该值。

The Question

我明白 Request["foo"]​​​ 没有值,但它不应该返回空字符串而不是null吗?即使没有值,是否有办法找出查询字符串键是否存在?

Notes

我在这里发现,Request.QueryString.AllKeys在空的查询字符串参数中包括null

[edit]

正如JamesDreas所述,使用正则表达式解析原始URL可能是最好(也可能是唯一)的方法。

Regex.IsMatch(Request.RawUrl, "[?&]thumb([&=]|$)")
最佳回答

You can use null as the key for the NameValueCollection and it will give you a comma-delimited list of parameter names that don t have values.

For http://example.com?bar=3&foo you would use Request.QueryString[null] and it would retrieve foo.

If you have more than one parameter name without a value, it will give you a value that is comma-delimited.

For http://example.com?bar=3&foo&test you would get foo,test as a value back.

Update:

You can actually use Request.QueryString.GetValues(null) to get the parameter names that don t have values.

问题回答

Request.ServerVariables["QUERY_STRING"] will return the query string, complete, as a string. Then search it using a Regex or IndexOf

You get null because the foo parameter doesn t have a value with it.

...What s the problem exactly?

If you still want to check for its existence (although it lacks a value), try something like this:

bool doesFooExist = Request.Url.AbsoluteUri.IndexOf("foo=") >= 0 ? true : false;

Dreas is correct. Variable "bar" has a value but foo does not.

QueryString["Bar"] will return 3 because it has the value 3 associated with the variable Bar. However, Foo will return null because their is no value and when you are calling QueryString on a variable or key, you are querying for the value, not the key, so that is why you are returning null.

query string is probably a waste one. If you use Request.Params[""] or iterate it, then you will find your desired one. Its really handy than other things.

Let me know if you need any help in this.





相关问题