Cookie没有在C#中设置 [英] Cookies not getting set in c#

查看:123
本文介绍了Cookie没有在C#中设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用cookie来了解是否已加载页面。因此,在asp.net c#页面的页面加载中,我使用的是

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.
}

并在if作为最后一个参数中设置如下所示的cookie值

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";
}

当我在本地主机上运行时,它的工作正常。但是,当我为每次页面加载(回发事件)将其托管到服务器时,初始if语句为true(即cookie始终为null)并进入循环。

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我做错了吗?
如何在c#中执行此操作?
谢谢

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

推荐答案

尝试设置cookie的失效日期,如果未设置cookie的失效日期,则默认情况下cookie,它将是非持久性的,并且仅作为会话信息的一部分存储,因此,当您关闭浏览器时,cookie将被丢弃,例如

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);

这篇关于Cookie没有在C#中设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆