加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 一种从WebApi中的HttpRequestHeaders中删除特定cookie的方

发布时间:2020-12-15 08:47:48 所属栏目:百科 来源:网络整理
导读:我正在尝试从ActionFilter的OnActionExecuted方法中删除HttpResponseHeaders中的特定Set-Cookie标头. 我遇到的问题很少: 我看不到枚举头的方式.这个系列总是如此 即使我在调试器中看到标题,也是空的. 因为我做不到 枚举,我无法删除特定的标题.我只能删除所
我正在尝试从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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读