我正在尝试从ActionFilter的OnActionExecuted方法中删除HttpResponseHeaders中的特定Set-Cookie标头.
我遇到的问题很少:
>我看不到枚举头的方式.这个系列总是如此
即使我在调试器中看到标题,也是空的.
>因为我做不到
枚举,我无法删除特定的标题.我只能删除所有
标题具有相同的键,但Set-Cookie可以有多个
条目.
目前我正在删除所有cookie,但这不是我想要的.
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { HttpResponseHeaders headers = actionExecutedContext.Response.Headers; IEnumerable<string> values; if (headers.TryGetValues("Set-Cookie",out values)) { actionExecutedContext.Response.Headers.Remove("Set-Cookie"); } base.OnActionExecuted(actionExecutedContext); }
解决方法
从
link:
You cannot directly delete a cookie on a user’s computer. However,you can direct the user’s browser to delete the cookie by setting the cookie’s expiration date to a past date. The next time a user makes a request to a page within the domain or path that set the cookie,the browser will determine that the cookie has expired and remove it.
那么,如何在动作过滤器级别删除/删除ASP.NET Web Api中的cookie,只需尝试将cookie的过期日期设置为过去的日期:
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { var response = actionExecutedContext.Response; var request = actionExecutedContext.Request; var currentCookie = request.Headers.GetCookies("yourCookieName").FirstOrDefault(); if (currentCookie != null) { var cookie = new CookieHeaderValue("yourCookieName","") { Expires = DateTimeOffset.Now.AddDays(-1),Domain = currentCookie.Domain,Path = currentCookie.Path }; response.Headers.AddCookies(new[] { cookie }); } base.OnActionExecuted(actionExecutedContext); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。