簡體   English   中英

有沒有辦法將所有查詢字符串名稱/值對放入一個集合中?

[英]Is there a way to get all the querystring name/value pairs into a collection?

有沒有辦法將所有查詢字符串名稱/值對放入一個集合中?

我正在尋找 .net 中的內置方式,如果沒有,我可以在 & 上拆分並加載一個集合。

是的,使用HttpRequest.QueryString集合:

獲取HTTP查詢字符串變量的集合。

你可以像這樣使用它:

foreach (String key in Request.QueryString.AllKeys)
{
    Response.Write("Key: " + key + " Value: " + Request.QueryString[key]);
}

好吧, Request.QueryString已經是一個集合。 具體來說,它是一個NameValueCollection 如果您的代碼在ASP.NET中運行,那就是您所需要的。

所以回答你的問題:是的,有。

您可以使用LINQ創建可以在數組中訪問的匿名對象列表:

var qsArray = Request.QueryString.AllKeys
    .Select(key => new { Name=key.ToString(), Value=Request.QueryString[key.ToString()]})
    .ToArray();

如果只有一個查詢字符串表示為字符串,請使用HttpUtility.ParseQueryString將其解析為NameValueCollection。

但是,如果這是HttpRequest的一部分,那么使用已經解析的HttpRequest的QueryString屬性。

HttpRequest類中的QueryString屬性實際上是NameValueCollection類。 你需要做的就是

NameValueCollection col = Request.QueryString;

創建參數字典

Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters = Request.QueryString.Keys.Cast<string>().ToDictionary(k => k, v => Request.QueryString[v]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM