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

wmomyfyw  于 2023-08-08  发布在  .NET
关注(0)|答案(9)|浏览(114)

error.aspx页面如果用户访问该页面,那么它将使用Request.QueryString["aspxerrorpath"]获取page_load()方法URL中的错误路径,并且它工作正常。
但是如果用户直接访问该页面,它将生成一个异常,因为aspxerrorpath不存在。
如何检查aspxerrorpath是否存在?

bhmjp9jg

bhmjp9jg1#

您可以查看null

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

字符串

vfh0ocws

vfh0ocws2#

检查参数的值:

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

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

字符串
如果它不存在,值将是null,如果它存在,但没有设置值,它将是一个空字符串。
我相信上面的代码比null的测试更适合您的需要,因为空字符串对于您的特定情况同样糟糕。

r7xajy2e

r7xajy2e3#

要检查空QueryString,您应该使用Request.QueryString.HasKeys属性。
检查密钥是否存在:Request.QueryString.AllKeys.Contains()
然后你可以获取ist的Value并做任何你想要的检查,比如isNullOrEmpty等等。

idv4meu8

idv4meu84#

您也可以尝试:

if (!Request.QueryString.AllKeys.Contains("aspxerrorpath"))
   return;

字符串

czfnxgou

czfnxgou5#

string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]) //true -> there is no value

字符串
如果有值,将返回

du7egjpx

du7egjpx6#

不如直接一点?

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

字符串

qpgpyjmq

qpgpyjmq7#

我想你要的支票是这个

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

字符串
它返回null,因为在该查询字符串中,该键没有值。

23c0lvtd

23c0lvtd8#

要解决问题,请在页面的Page_Load方法上写入以下行。

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

字符串
.Net 4.0提供了对null、empty或whitespace字符串的更深入的了解,请按以下行所示使用它:

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


如果查询字符串没有aspxerrorpath,这将不会运行您的下一个语句(您的业务逻辑)。

oxf4rvwz

oxf4rvwz9#

//使用Haskeys()和GetKey(0)

if (Request.QueryString.HasKeys() && Request.QueryString.GetKey(0) == "aspxerrorpath")
    {
        //It has a key and the key is valid
        string KeyValueByIndex = Request.QueryString[0];
        //OR
        string KeyValueByName = Request.QueryString["aspxerrorpath"];
    }
    else
    {
        //else...
    }

字符串

相关问题