基本上,我試圖從cookie中獲取字符串值。立即訪問cookie,不會導致重複
如果我從請求中讀取它,我可以得到正確的值。 除了第一次頁面加載,因爲響應還沒有發送到客戶端,所以請求沒有我剛剛設置的值。
但是,奇怪的是..如果我訪問Response並檢查它是否存在(又名value剛剛設置)..我可以得到這個值。但是它會導致一些奇怪的錯誤(?),在下一次返回時cookie會在請求中被複制。
在第二個請求返回..而是從空白的重複請求cookie中讀取值。 (換言之,cookie值不工作)
SAVE
var request = url.RequestContext.HttpContext.Request;
var response = url.RequestContext.HttpContext.Response;
//STORE VALUES TO COOKIE
HttpCookie hc = new HttpCookie("myCookie");
hc.Expires = DateTime.Now.AddDays(1);
hc.Value = "MYVALUE";
request.Cookies.Add(hc);
response.Cookies.Add(hc);
閱讀
public static string GetAdvancedCookieValue(this UrlHelper url, string cookieName)
{
var request = url.RequestContext.HttpContext.Request;
var response = url.RequestContext.HttpContext.Response;
// Accessing Response allows me to get value just set.. but leads to duplicate cookies (with blank data -causing blank return later)
if (response.Cookies[cookieName] != null && String.IsNullOrWhiteSpace(response.Cookies[cookieName].Value) == false)
return response.Cookies[cookieName].Value;
if (request.Cookies[cookieName] != null && String.IsNullOrWhiteSpace(request.Cookies[cookieName].Value) == false)
return request.Cookies[cookieName].Value;
return null;
}
直到我添加一個響應中的cookies才存在。我認爲加入迴應應該用這個名字覆蓋現有的?我找到了一個解決方案,雖然不能確定它的理想。 – Doomsknight
我想這個代碼反正只是櫃面我錯過了一些東西,它不工作:(雖然欣賞的幫助! – Doomsknight