简体   繁体   中英

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.

C# Code:

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:

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. I wanted to read the cookie value once it is created in the same post back.

But only in the next post back the doLogic method is able to get the cookie value.

Isn't it the case that you can't read testCookie because it isn't a part of Request.Cookies? In other words, you created the cookie after the request was generated. 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? I think that's what is going on here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM