diff --git a/NLog.Web.ASPNET5.Tests/LayoutRenderers/AspNetRequestValueLayoutRendererTests.cs b/NLog.Web.ASPNET5.Tests/LayoutRenderers/AspNetRequestValueLayoutRendererTests.cs index 735409c9..e30f4f0f 100644 --- a/NLog.Web.ASPNET5.Tests/LayoutRenderers/AspNetRequestValueLayoutRendererTests.cs +++ b/NLog.Web.ASPNET5.Tests/LayoutRenderers/AspNetRequestValueLayoutRendererTests.cs @@ -1,7 +1,11 @@ using System.Collections.Specialized; +using System.IO; using System.Web; +using NLog.Common; +using NLog.Config; using NLog.Web.LayoutRenderers; using NSubstitute; +using NSubstitute.ExceptionExtensions; using Xunit; namespace NLog.Web.Tests.LayoutRenderers @@ -18,6 +22,26 @@ public void NullHttpContextRendersEmptyString() Assert.Empty(result); } + [Fact] + public void NullRequestRendersEmptyStringWithoutLoggingError() + { + var internalLog = new StringWriter(); + InternalLogger.LogWriter = internalLog; + InternalLogger.LogLevel = LogLevel.Error; + + var httpContext = Substitute.For(); + httpContext.Request.Returns(x => { throw new HttpException(); }); + + var renderer = new AspNetRequestValueLayoutRenderer(); + renderer.HttpContextAccessor = new FakeHttpContextAccessor(httpContext); + renderer.Item = "key"; + + string result = renderer.Render(new LogEventInfo()); + + Assert.Empty(result); + Assert.Equal(true, string.IsNullOrEmpty(internalLog.ToString())); + } + public class ItemTests { [Fact] diff --git a/NLog.Web.ASPNET5/LayoutRenderers/AspNetRequestValueLayoutRenderer.cs b/NLog.Web.ASPNET5/LayoutRenderers/AspNetRequestValueLayoutRenderer.cs index 302edff3..27bc6ded 100644 --- a/NLog.Web.ASPNET5/LayoutRenderers/AspNetRequestValueLayoutRenderer.cs +++ b/NLog.Web.ASPNET5/LayoutRenderers/AspNetRequestValueLayoutRenderer.cs @@ -1,5 +1,6 @@ using System; using System.Text; +using NLog.Common; #if !DNX using System.Web; #else @@ -76,7 +77,7 @@ public class AspNetRequestValueLayoutRenderer : AspNetLayoutRendererBase /// Logging event. protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent) { - var httpRequest = HttpContextAccessor.HttpContext.Request; + var httpRequest = HttpContextAccessor.HttpContext.TryGetRequest(); if (httpRequest == null) { return; @@ -137,4 +138,28 @@ protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent) } } } + + internal static class RequestAccessor + { +#if !DNX + internal static HttpRequestBase TryGetRequest(this HttpContextBase context) + { + try + { + return context.Request; + } + catch (HttpException ex) + { + InternalLogger.Debug("Exception thrown when accessing Request: " + ex); + return null; + } + } +#else + internal static HttpRequest TryGetRequest(this HttpContext context) + { + return context.Request; + } +#endif + } + } \ No newline at end of file