简体   繁体   English

如何在ASP.NET中检查Request.QueryString是否具有特定值?

[英]How to check that Request.QueryString has a specific value or not in ASP.NET?

I have an error.aspx page. 我有一个error.aspx页面。 If a user comes to that page then it will fetch the error path in page_load() method URL using Request.QueryString["aspxerrorpath"] and it works fine. 如果用户访问该页面,它将使用Request.QueryString["aspxerrorpath"]page_load()方法URL中获取错误路径,并且可以正常工作。

But if a user directly accesses that page the it will generate an exception because aspxerrorpath is not there. 但是,如果用户直接访问该页面,则它将生成异常,因为aspxerrorpath不存在。

How can I check that aspxerrorpath is there or not? 如何检查aspxerrorpath是否存在?

You can just check for null : 您可以只检查null

if(Request.QueryString["aspxerrorpath"]!=null)
{
   //your code that depends on aspxerrorpath here
}

Check for the value of the parameter: 检查参数的值:

// .NET < 4.0
if (string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]))
{
 // not there!
}

// .NET >= 4.0
if (string.IsNullOrWhiteSpace(Request.QueryString["aspxerrorpath"]))
{
 // not there!
}

If it does not exist, the value will be null , if it does exist, but has no value set it will be an empty string. 如果不存在,则该值为null ;如果确实存在,但未设置任何值,则该值为空字符串。

I believe the above will suit your needs better than just a test for null , as an empty string is just as bad for your specific situation. 我相信以上内容将比仅仅测试null更适合您的需求,因为空字符串对您的特定情况同样有害。

To check for an empty QueryString you should use Request.QueryString.HasKeys property. 若要检查空的QueryString,应使用Request.QueryString.HasKeys属性。

To check if the key is present: Request.QueryString.AllKeys.Contains() 要检查密钥是否存在: Request.QueryString.AllKeys.Contains()

Then you can get ist's Value and do any other check you want, such as isNullOrEmpty, etc. 然后,您可以获取ist的Value并执行所需的其他任何检查,例如isNullOrEmpty等。

You can also try: 您也可以尝试:

if (!Request.QueryString.AllKeys.Contains("aspxerrorpath"))
   return;
string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]) //true -> there is no value

如果有值将返回

那更直接的方法呢?

if (Request.QueryString.AllKeys.Contains("mykey")

think the check you're looking for is this: 认为您要查找的支票是这样的:

if(Request.QueryString["query"] != null) 

It returns null because in that query string it has no value for that key. 它返回null因为在该查询字符串中,该键没有任何值。

To resolve your problem, write the following line on your page's Page_Load method. 要解决您的问题,请在页面的Page_Load方法上写以下行。

if (String.IsNullOrEmpty(Request.QueryString["aspxerrorpath"])) return;

.Net 4.0 provides more closer look to null, empty or whitespace strings, use it as shown in the following line: .Net 4.0可以更仔细地查看null,空字符串或空格字符串,如下行所示使用它:

if(string.IsNullOrWhiteSpace(Request.QueryString["aspxerrorpath"])) return;

This will not run your next statements (your business logics) if query string does not have aspxerrorpath. 如果查询字符串没有aspxerrorpath,这将不会运行您的下一个语句(您的业务逻辑)。

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

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