[英]Unable to read the cookie created dynamically in ASP C# application
I'm creating a cookie from the code behind by calling a js method (using Page.ClientScript.RegisterStartupScript ) in the button click event, once created i'm trying to use the cookie value to work my logic but i'm not able to read the cookie until the next page load. 我正在通过在按钮click事件中调用js方法(使用Page.ClientScript.RegisterStartupScript )从背后的代码创建cookie,一旦创建,我就试图使用cookie值来实现我的逻辑,但是我无法读取Cookie,直到加载下一页。
C# Code: C#代码:
protected void submitKey(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function", " createCookie('testvalue');", true);
vendorManagementDiv.Style.Add("display", "block");
doLogic();
}
private String doLogic{
var request = HttpContext.Current.Request;
HttpCookieCollection cookies = request.Cookies;
foreach (String cookieName in cookies.AllKeys)
{
if (cookieName.Equals("testcookie"))
{
key = request.Cookies["testcookie"].Value;
}
}
return key;
}
JS function: JS功能:
function createCookie(cookievalue)
{
var expires = "";
var date = new Date();
date.setTime(date.getTime() + (1 * 24 * 60 * 60 * 1000));
expires = ";expires=" + date.toGMTString();
document.cookie = "testcookie=" + cookievalue+ expires + ";path=/";
}
Issue here is i'm not able to read the value of the cookie 'testcookie' in the doLogic method that is called. 这里的问题是我无法在调用的doLogic方法中读取cookie'testcookie'的值。 I wanted to read the cookie value once it is created in the same post back. 我想在同一回发中创建cookie值后读取它。
But only in the next post back the doLogic method is able to get the cookie value. 但是只有在下一篇文章中,doLogic方法才能获取cookie值。
Isn't it the case that you can't read testCookie because it isn't a part of Request.Cookies? 是不是因为它不是Request.Cookies的一部分而无法阅读testCookie的情况? In other words, you created the cookie after the request was generated. 换句话说,您在生成请求之后创建了cookie。 In that case, wouldn't your new cookie not be in the list of Request.Cookies because the cookie didn't exist at that time? 在这种情况下,您的新cookie不会不在Request.Cookies列表中,因为那时cookie不存在吗? I think that's what is going on here. 我认为这就是正在发生的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.