更新 ASP.NET 中先前请求中设置的 cookie 的最佳实践是什么?
这是场景。已在之前的请求中设置了带有 "MyCookie"
键的 cookie。我可以通过 HttpContext.Request.Cookies.Get("MyCookie") 访问它。我想要执行更新,例如向 Cookie Values 集合添加另一个值,但我不能 100% 确定我做得正确。
我在下面的例子中这样做正确吗?
public static void UpdateCookie(HttpContext context, string cookieName, Action<HttpCookie> updateCookie){
var cookie = context.Request.Cookies.Get(cookieName);
updateCookie(cookie);
context.Response.Cookies.Set(cookie);
}
Here is the scenario. A cookie with the key "MyCookie"
has been set on a previous request. I can access it via HttpContext.Request.Cookies.Get("MyCookie")
. I want to perform an update such as adding another value to the Cookie Values collection, but I'm not 100% sure I am doing it right.
Am I doing this correctly in the following example?
public static void UpdateCookie(HttpContext context, string cookieName, Action<HttpCookie> updateCookie){
var cookie = context.Request.Cookies.Get(cookieName);
updateCookie(cookie);
context.Response.Cookies.Set(cookie);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要更新 cookie,您只需使用新值再次设置 cookie。请注意,您必须包含要保留的所有数据,因为新的 cookie 将替换之前设置的 cookie。我假设您的 updateCookie() 实现就是这样做的。
否则,你的一般前提是正确的。这是我多次使用的实现。 (注:_page是对当前Page的引用):
To update a cookie, you need only to set the cookie again using the new values. Note that you must include all of the data you want to retain, as the new cookie will replace the previously set cookie. I'm going to assume that your implementation of updateCookie() does just that.
Otherwise, your general premise is correct. Here's an implementation I've used many times to do just that. (Note: _page is a reference to the current Page):