19

在 ASP.NET 页面的上下文中,我可以使用 Request.QueryString 来获取 URI 的查询字符串部分中的键/值对的集合。

例如,如果我使用 加载我的页面http://local/Default.aspx?test=value,那么我可以调用以下代码:

//http://local/Default.aspx?test=value

protected void Page_Load(object sender, EventArgs e)
{
    string value = Request.QueryString["test"]; // == "value"
}

理想情况下,我想做的是检查test是否存在,所以我可以调用页面http://local/Default.aspx?test并获取一个布尔值,告诉我查询字符串中是否存在 test。像这样的东西:

//http://local/Default.aspx?test

protected void Page_Load(object sender, EventArgs e)
{
    bool testExists = Request.QueryString.HasKey("test"); // == True
}

所以理想情况下,我想要的是一个布尔值,它告诉我测试变量是否存在于字符串中。

我想我可以只使用正则表达式来检查字符串,但我很好奇是否有人有更优雅的解决方案。

我尝试了以下方法:

//http://local/Default.aspx?test

Request.QueryString.AllKeys.Contains("test"); // == False  (Should be true)
Request.QueryString.Keys[0];                  // == null   (Should be "test")
Request.QueryString.GetKey(0);                // == null   (Should be "test")

这种行为与 PHP 不同,例如,我可以在其中使用

$testExists = isset($_REQUEST['test']); // == True
4

6 回答 6

27

Request.QueryString.GetValues(null)将得到一个没有值的键列表

Request.QueryString.GetValues(null).Contains("test")将返回真

于 2013-02-15T19:50:56.777 回答
5

我写了一个扩展方法来解决这个任务:

public static bool ContainsKey(this NameValueCollection collection, string key)
{
    if (collection.AllKeys.Contains(key)) 
        return true;

     // ReSharper disable once AssignNullToNotNullAttribute
    var keysWithoutValues = collection.GetValues(null);
    return keysWithoutValues != null && keysWithoutValues.Contains(key);
}
于 2013-10-10T11:21:18.963 回答
2

Request.QueryString是 a NameValueCollection,但只有在查询字符串采用通常[name=value]*格式时才会将项目添加到其中。如果不是,则为空。

如果你QueryString的形式是?test=value,那么Request.QueryString.AllKeys.Contains("test")会做你想做的事。否则,您将被困在Request.Url.Query.

于 2013-02-15T19:46:40.733 回答
2

我用这个。

if (Request.Params["test"] != null)
{
    //Is Set
}
else if(Request.QueryString.GetValues(null) != null && 
       Array.IndexOf(Request.QueryString.GetValues(null),"test") > -1)
{
    //Not set
}
else
{
    //Does not exist
}
于 2016-01-14T17:53:35.377 回答
1

试试这个,它解决了我的问题!它将计算查询字符串是否有值或为空,然后您可以使用键检查所需的查询字符串值。

  if (!Page.IsPostBack)
        {
           if (Request.QueryString.Count > 0)
            {
                if (Request.QueryString["departmentId"] != null)
                {
                    GetSurveyByDeptAndStatus(departmentId: Request.QueryString["departmentId"], status: "Not Surveyed");
                    rbListEmpsSurvey.Items[1].Selected = true;
                }

                else if (Request.QueryString["SurveyStatus"] != null)
                {
                    SatisfactionStatus = Request.QueryString["SurveyStatus"] "";
                    GetSurveyByDeptAndStatus(status: SatisfactionStatus);
                    GetDepartments();
                }}}
于 2021-02-18T10:37:55.583 回答
-2
Request.QueryString.ToString().Contains("test")

这适用于您正在寻找单个查询字符串参数的特殊情况,例如MyFile.aspx?test

对于更复杂、更一般的情况,其他解决方案会更好。

于 2013-11-01T18:13:09.947 回答