如何在C#中创建一个非持久的(在内存中)http cookie? [英] How to create a non-persistent (in memory) http cookie in C#?

查看:62
本文介绍了如何在C#中创建一个非持久的(在内存中)http cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的cookie在用户关闭浏览器时消失-我已经设置了一些很有前途的属性,但是即使关闭整个浏览器后,我的cookie也会重新显示出来.

I want my cookie to disappear when the user closes their brower-- I've already set some promising looking properties, but my cookies pop back to live even after closing the entire browser.

HttpCookie cookie = new HttpCookie("mycookie", "abc");
cookie.HttpOnly = true; //Seems to only affect script access
cookie.Secure = true; //Seems to affect only https transport

我缺少实现内存中cookie的哪些属性或方法调用?

What property or method call am I missing to achieve an in memory cookie?

推荐答案

此问题已在线发布1000多次.在浏览器打开的情况下处理非持久性Cookie超时的最佳方法是为超时添加一个键值.以下代码用于登录用户ID密钥值和加密(不包括)安全性,以实现浏览器兼容性.我不使用表单身份验证.

This question has been posted online 1000+ times. The best way to handle non-persistent cookies timeout with the browser open is add a key value for timeout. The code below is used for a log in user id key value and encryption(not included) security for browser compatibility. I do not use forms authentication.

HttpCookie cookie = new HttpCookie(name);
cookie.Values["key1"] = value;
cookie.Values["key2"] = DateTime.Now.AddMinutes(70).ToString(); 
                             //timeout 70 minutes with browser open
cookie.Expires = DateTime.MinValue;
cookie.Domain = ConfigurationManager.AppSettings["website_domain"];
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);

在检查cookie键值时,请使用:

When checking the cookie key value use:

try
{

DateTime dateExpireDateTime;
dateExpireDateTime = DateTime.Parse(HttpContext.Current.Request.Cookies[name]["key2"]);

if (DateTime.Now > dateExpireDateTime)
{
//cookie key value timeout code
}
else
{
//reset cookie
}

catch
{
//clear cookie and redirect to log in page
}

我发现使用表单身份验证和Google Chrome浏览器存在兼容性问题.

I have found compatibility issues using forms authentication and Google Chrome.

这篇关于如何在C#中创建一个非持久的(在内存中)http cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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