diff --git a/src/Microsoft.AspNetCore.Server.HttpSys/MessagePump.cs b/src/Microsoft.AspNetCore.Server.HttpSys/MessagePump.cs index 53330c6f1c..00a28df87c 100644 --- a/src/Microsoft.AspNetCore.Server.HttpSys/MessagePump.cs +++ b/src/Microsoft.AspNetCore.Server.HttpSys/MessagePump.cs @@ -204,17 +204,18 @@ namespace Microsoft.AspNetCore.Server.HttpSys { await _application.ProcessRequestAsync(context).SupressContext(); await featureContext.OnResponseStart(); - requestContext.Dispose(); - _application.DisposeContext(context, null); } finally { await featureContext.OnCompleted(); } + _application.DisposeContext(context, null); + requestContext.Dispose(); } catch (Exception ex) { LogHelper.LogException(_logger, "ProcessRequestAsync", ex); + _application.DisposeContext(context, ex); if (requestContext.Response.HasStarted) { requestContext.Abort(); @@ -225,7 +226,6 @@ namespace Microsoft.AspNetCore.Server.HttpSys requestContext.Response.Headers.Clear(); SetFatalResponse(requestContext, 500); } - _application.DisposeContext(context, ex); } finally { diff --git a/test/Microsoft.AspNetCore.Server.HttpSys.FunctionalTests/AuthenticationTests.cs b/test/Microsoft.AspNetCore.Server.HttpSys.FunctionalTests/AuthenticationTests.cs index 87a712fa24..7a4a184087 100644 --- a/test/Microsoft.AspNetCore.Server.HttpSys.FunctionalTests/AuthenticationTests.cs +++ b/test/Microsoft.AspNetCore.Server.HttpSys.FunctionalTests/AuthenticationTests.cs @@ -5,6 +5,7 @@ using System; using System.Linq; using System.Net; using System.Net.Http; +using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Testing.xunit; @@ -165,6 +166,34 @@ namespace Microsoft.AspNetCore.Server.HttpSys } } + // https://github.com/aspnet/Logging/issues/543#issuecomment-321907828 + [ConditionalFact] + public async Task AuthTypes_AccessUserInOnCompleted_Success() + { + var completed = new ManualResetEvent(false); + string userName = null; + var authTypes = AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM; + using (var server = Utilities.CreateDynamicHost(authTypes, DenyAnoymous, out var address, httpContext => + { + Assert.NotNull(httpContext.User); + Assert.NotNull(httpContext.User.Identity); + Assert.True(httpContext.User.Identity.IsAuthenticated); + httpContext.Response.OnCompleted(() => + { + userName = httpContext.User.Identity.Name; + completed.Set(); + return Task.FromResult(0); + }); + return Task.FromResult(0); + })) + { + var response = await SendRequestAsync(address, useDefaultCredentials: true); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.True(completed.WaitOne(TimeSpan.FromSeconds(5))); + Assert.False(string.IsNullOrEmpty(userName)); + } + } + [ConditionalTheory] [InlineData(AuthenticationSchemes.Negotiate)] [InlineData(AuthenticationSchemes.NTLM)]