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

Pee*_*ush 68 .net c# asp.net

我有一个error.aspx页面.如果用户访问该页面,那么它将page_load()使用方法URL 获取错误路径,Request.QueryString["aspxerrorpath"]并且工作正常.

但是如果用户直接访问该页面,它将生成异常,因为aspxerrorpath不存在.

我该如何检查aspxerrorpath是否存在?

Bro*_*ass 108

你可以检查null:

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

  • @Peeyush你可能会发现你试图将它转换为'.ToString()',因此在测试null值本身之前尝试将null转换为字符串值.这是一个常见的错误. (4认同)
  • 在 Mvc 核心中它是 request.Query.ContainsKey("aspxerrorpath") (2认同)

Ode*_*ded 35

检查参数的值:

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

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

如果它不存在,则该值将是null,如果它确实存在,但没有设置值,则它将是一个空字符串.

我相信上面的内容更适合您的需求,而不仅仅是测试null,因为空字符串对于您的具体情况同样糟糕.

  • 如果 .NET == 4.0 呢?使用`IsNullOrWhiteSpace`? (2认同)

小智 12

要检查空的QueryString,您应该使用Request.QueryString.HasKeysproperty.

要检查密钥是否存在: Request.QueryString.AllKeys.Contains()

然后你可以获得ist的Value并进行你想要的任何其他检查,例如isNullOrEmpty等.

  • `Request.QueryString.AllKeys.Contains()`当密钥存在但实际上没有值时将返回false. (5认同)

sha*_*cov 9

你也可以尝试:

if (!Request.QueryString.AllKeys.Contains("aspxerrorpath"))
   return;
Run Code Online (Sandbox Code Playgroud)


Pet*_*ter 8

string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]) //true -> there is no value
Run Code Online (Sandbox Code Playgroud)

如果有值,将返回


Pro*_*ofK 6

更直接的方法怎么样?

if (Request.QueryString.AllKeys.Contains("mykey")
Run Code Online (Sandbox Code Playgroud)