在页面事件(例如加载)时,我是否使用“response”,因为这是来自ASP.NET的响应,而在按按钮时使用“request”,因为这是要发送给ASP.NET进行处理的响应?还是有更多需要注意的地方?
它们是两个不同的东西,一个保存[响应],另一个读取[请求]。
在Cookie中(从信息学角度来看),你可以保存一个包含字符串对象的小文件一段时间
在.NET框架中,你可以使用以下方法保存cookie:
HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);
// Add the cookie.
Response.Cookies.Add(myCookie);
Response.Write("<p> The cookie has been written.");
你写了一个cookie,它将在一分钟内可用...通常我们会使用now.AddMonth(1)来保存一个持续一个月的cookie。
要检索一个cookie,你可以使用请求(Request),例如:
HttpCookie myCookie = Request.Cookies["MyTestCookie"];
// Read the cookie information and display it.
if (myCookie != null)
Response.Write("<p>"+ myCookie.Name + "<p>"+ myCookie.Value);
else
Response.Write("not found");
记住:
要删除一个 Cookie,没有直接的代码,诀窍在于使用已经过期的时间来保存相同名称的 Cookie,例如now.AddMinutes(-1),这将会删除该 Cookie。
正如您所看到的,每当 Cookie 的生命周期到期时,该文件就会被系统自动删除。
在Web应用程序中,请求是来自浏览器的内容,响应是服务器返回的内容。当验证来自浏览器的Cookie或Cookie数据时,应使用Request.Cookies。当您构建要发送到浏览器的Cookie时,需要将它们添加到Response.Cookies中。
当编写Cookie时,请使用Response,但读取可能取决于您的情况。通常,您从Request中读取,但如果您的应用程序尝试获取刚编写或更新的Cookie,并且还没有回传到浏览器,则可能需要从Response中读取。
我已经使用这种模式一段时间了,对我来说效果很好。
public void WriteCookie(string name, string value)
{
var cookie = new HttpCookie(name, value);
HttpContext.Current.Response.Cookies.Set(cookie);
}
public string ReadCookie(string name)
{
if (HttpContext.Current.Response.Cookies.AllKeys.Contains(name))
{
var cookie = HttpContext.Current.Response.Cookies[name];
return cookie.Value;
}
if (HttpContext.Current.Request.Cookies.AllKeys.Contains(name))
{
var cookie = HttpContext.Current.Request.Cookies[name];
return cookie.Value;
}
return null;
}
Cookie来自于Request.Cookies集合中的浏览器。您需要在那里读取发送的cookie。
要将cookie发送回浏览器,您需要将它们放入Response.Cookies集合中。
如果您想要删除一个cookie,您必须告诉浏览器通过发送一个已过期的cookie来删除它。浏览器使用客户端计算机的本地时间,因此如果您使用服务器时间创建日期,请确保至少减去一天以确保它实际上已经在客户端的本地时间中过期。
当我在.NET中创建或更新cookie时,通常会同时对请求和响应cookie集合进行操作。这样,如果您尝试在页面请求序列的后面读取cookie,您可以确信它将具有正确的信息。
Andrew的代码在"AllKeys.Contains"方法中出现了错误。所以我进行了一些修正。
public void WriteCookie(string strCookieName, string strCookieValue)
{
var hcCookie = new HttpCookie(strCookieName, strCookieValue);
HttpContext.Current.Response.Cookies.Set(hcCookie);
}
public string ReadCookie(string strCookieName)
{
foreach (string strCookie in HttpContext.Current.Response.Cookies.AllKeys)
{
if (strCookie == strCookieName)
{
return HttpContext.Current.Response.Cookies[strCookie].Value;
}
}
foreach (string strCookie in HttpContext.Current.Request.Cookies.AllKeys)
{
if (strCookie == strCookieName)
{
return HttpContext.Current.Request.Cookies[strCookie].Value;
}
}
return null;
}
HttpCookie myCookie = new HttpCookie("MyTestCookie");
覆盖了之前保存的cookie。相反,应该使用类似这样的代码HttpCookie myCookie = new HttpCookie("MyWrittenCookie");
。 - Off The GoldResponse.Cookies
。 - ajbeavenRequest.Cookies[""].Value
与我在浏览器中看到的值以及实际存储的值不同?我使用浏览器控制台检查了 cookie 的值。 - Mehdi Dehghani