【问题标题】:Remove Cookie from Web API 2 Response从 Web API 2 响应中删除 Cookie
【发布时间】:2014-02-07 15:07:14
【问题描述】:

我正在尝试执行一个经过身份验证的 Web api 请求,该请求不会重置身份验证 cookie 超时。在 MVC 世界中,我将通过从响应中删除 FormsAuthenication cookie 来完成此操作:

 Response.Cookies.Remove(System.Web.Security.FormsAuthentication.FormsCookieName);

在 Web API 2 中,我编写了一个自定义 IHttpActionResult,并从响应中删除了 Set-Cookie 标头。然而,这并没有删除标头,因为当为使用此操作结果的请求更新 auth cookie 时,我仍然看到 Set-Cookie 标头。

这是自定义的 IHttpActionResult:

public class NonAuthResetResult<T> : IHttpActionResult where T: class
{
    private HttpRequestMessage _request;
    private T _body;

    public NonAuthResetResult(HttpRequestMessage request, T body)
    {
        _request = request;
        _body = body;
    }

    public string Message { get; private set; }

    public HttpRequestMessage Request { get; private set; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var msg = _request.CreateResponse(_body);
        msg.Headers.Remove("Set-Cookie");
        return Task.FromResult(msg);
    }
}

如何在 Web API 2 中编辑响应标头,因为这不起作用。

【问题讨论】:

    标签: c# asp.net-web-api asp.net-web-api2


    【解决方案1】:

    Global.asax 可以在 Application_EndRequest 事件中删除 cookie。您可以设置一个变量,以便稍后由 Application_EndRequest 获取。

    步骤 1. 创建一个在 Context.Items 中设置变量的操作过滤器:

    public class NoResponseCookieAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            System.Web.HttpContext.Current.Items.Add("remove-auth-cookie", "true");
        }
    }
    

    第 2 步。处理 global.asax 文件中的 Application_EndRequest 事件。如果存在步骤 1 中的变量,请删除 cookie。

    protected void Application_EndRequest()
    {
        if (HttpContext.Current.Items["remove-auth-cookie"] != null)
        {
            Context.Response.Cookies.Remove(System.Web.Security.FormsAuthentication.FormsCookieName);
        }
    }
    

    第 3 步。使用自定义过滤器装饰您的 Web api 操作:

    [NoResponseCookie]
    public IHttpActionResult GetTypes()
    {
        // your code here
    }
    

    【讨论】:

      【解决方案2】:

      如果您使用的是 Web API 2,那么您可能使用的是 OWIN Cookie 中间件。您所描述的内容听起来像是您想禁用身份验证 cookie 上的滑动到期窗口。

      在标准 Web API 模板中,您应该有一个 App_Start/Startup.Auth.cs。在里面你会找到这条线......

      app.UseCookieAuthentication(new CookieAuthenticationOptions());
      

      这会启用和配置 cookie 中间件。您可以传入一些选项来更改超时窗口并禁用滑动到期...

      app.UseCookieAuthentication(new CookieAuthenticationOptions
      {
          SlidingExpiration = false,
          ExpireTimeSpan = new TimeSpan(1, 0, 0) // 1 hour
      });
      

      【讨论】:

      • 我需要针对特定​​请求执行此操作。不是全局 Web API 设置。
      猜你喜欢
      • 2021-02-09
      • 2013-07-09
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      相关资源
      最近更新 更多