【问题标题】:Stop request in CookieAuthenticationEvents.OnValidatePrincipal after response body has been written to响应正文写入后,在 CookieAuthenticationEvents.OnValidatePrincipal 中停止请求
【发布时间】:2021-07-01 04:20:33
【问题描述】:

OnValidatePrincipal,我有以下代码:

async (context) =>
{
    await context.HttpContext.SignOutAsync();
    context.Principal = null;
    context.Response.StatusCode = 452;
    await context.Response.WriteAsJsonAsync(new { Description = "Sample description"});
    await context.Response.Body.FlushAsync();
}

但由于某种原因,请求继续到它最初指向的位置,执行操作及其背后的代码。

我不确定这是否是一个错误,但已经编写了响应 - 继续执行请求最初指向的操作/端点似乎毫无意义。有没有办法阻止这种情况?

即使正在执行的操作返回不同的响应,ASP.NET Core 也正确返回了我在 OnValidatePrincipal 中写入的响应,可能是由于刷新它,锁定了流以防止进一步写入?

【问题讨论】:

    标签: c# asp.net-core authentication cookies asp.net-core-middleware


    【解决方案1】:

    我已经通过使用定制的中间件解决了这个问题:

    /// <summary>
    /// A middleware that short-circuits the request's pipeline, if a response has already been started.
    /// </summary>
    public class EnsureResponseNotStartedMiddleware
    {
        private readonly RequestDelegate _nextMiddleware;
    
        public EnsureResponseNotStartedMiddleware(RequestDelegate nextMiddleware)
        {
            _nextMiddleware = nextMiddleware;
        }
    
        public Task InvokeAsync(HttpContext context)
        {
            if (!context.Response.HasStarted)
            {
                return _nextMiddleware(context);
            }
    
            return Task.CompletedTask;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多