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

前端之家收集整理的这篇文章主要介绍了c# – 一种从WebApi中的HttpRequestHeaders中删除特定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);
}

猜你在找的C#相关文章