c# - ASP.NET Set cookie ONLY if empty Value -
i trying set cookie when user access webpage. value of cookie unique number store on database keep track of when user comes website. set cookie in global.asax follow:
void application_beginrequest() { string cookievalue = ""; string = ""; try { = getcookie(); if (!string.isnullorempty(a)) { cookievalue = a; } else { cookievalue = setcookie(); } } catch (exception ex) { } }
in beginrequest() want check if cookie exist. if exist, nothing , keep value inside cookie. if doesn't exist, set cookie , add value.
public static string getcookie() { string cookievalue = ""; try { if (httpcontext.current.request.cookies["testcookie"] != null) cookievalue = httpcontext.current.response.cookies["testcookie"].value; } catch (exception ex) { // } return cookievalue; } public static string setcookie() { string cookievalue = ""; try { httpcookie mycookie = new httpcookie("testcookie"); // set cookie value. mycookie.value = "1234"; //1234 unique number mycookie.expires = datetime.now.addyears(50); httpcontext.current.response.cookies.add(mycookie); cookievalue = id; } catch (exception ex) { // } return cookievalue; }
the problem everytime reload page, "testcookie" gets rewritten new value. have been reading msdn how cookies stored in asp.net , according instructions, way supposed work fine. must doing wrong cannot see it. had code inside normal page e.g. test.aspx.cs test had same result , decided move application level , see if make difference did not :(.
Comments
Post a Comment