Cookies not getting set in c#

无人久伴 提交于 2020-01-06 13:56:38

问题


I am using cookies to know whether a page was loaded before or not. So in page load of a asp.net c# page I am using this

if (Request.Cookies["PageLoaded"] == null)
{
   //Initialize things if page loading for first time.
}

and inside the if as last parameter I am setting the cookies value like given below

if (Request.Cookies["PageLoaded"] == null)
{
   //Initialize things if page loading for first time.

   //Set cookies value to indicate page has loaded before
   Response.Cookies["PageLoaded"].Value = "True";
}

When I run in local host its working fine. But when I host it to server for each page load(Postback events) the initial if statement is true(ie cookie is always null) and going inside the loop.

Am I doing something wrong? How can I do this in c#? Thanks


回答1:


Try setting an expiry date for your cookie, by default if you do not set an expiry date for the cookie it will be non-persistant and only stored as part of the Session information so when you close the browser the Cookie will be discarded e.g.

Response.Cookies["PageLoaded"].Value = "True";
Response.Cookies["PageLoaded"].Expires = DateTime.Now.AddDays(1);


来源:https://stackoverflow.com/questions/7399717/cookies-not-getting-set-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!