[英]C#, getting cookies with different names
我根據引薦鏈接設置了cookie,它們都以相同的字母開頭,以“ google”開頭,但是以_xxx,_yyy,_zzz或其他任何引用結尾。
現在,當我稍后嘗試獲取Cookie時,出現了一個問題,就是我不想檢查所有不同的cookie,我想檢查所有以“ google”開頭的cookie,並在此基礎上啟動一個繼續處理的腳本。
if (Request.Cookies("google"))
{
run other stuff
}
知道如何添加StartWith或其他東西嗎? 我是新手,所以還沒真正融入C#中。
提前致謝,
拍
好吧。HttpRequest.Cookies 是一個集合。 因此,使用LINQ:
var qry = from cookieName in Request.Cookies.Keys
where cookieName.StartsWith("google")
select cookieName;
foreach(var item in qry)
{
// get the cookie and deal with it.
var cookie = Request.Cookies[item];
}
底線:您無法避免遍歷整個cookie集合。 但是您可以使用LINQ輕松地做到這一點。
如果要查找帶有特定后綴的cookie,則必須檢查所有cookie(Randolpho的答案會起作用)。
這樣做不是一個特別好的主意。 問題在於,創建的Cookie越多,則服務器和連接上的開銷就越大。 假設您有10個Cookie: google_aaa
, google_bbb
等。每個請求都會將所有10個cookie發送到您的服務器(包括對圖像,css等的請求。
最好使用單個cookie,它是存儲在服務器上所有信息的某種鑰匙。 像這樣:
var cookie = Cookies["google"];
if(cookie!=null)
{
// cookie.Value is a unique key for this user. Lookup this
// key in your database or other store to find out the
// information about this user.
}
如果願意,可以使用lambda表達式
var cookie = Request.Cookies.AllKeys.FirstOrDefault(s => s.Contains("yourName"));
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.