Skip to content

Commit

Permalink
Suppressing exception thrown when accessing HttpContext.Request (#56)
Browse files Browse the repository at this point in the history
* Suppressing exception thrown when accessing HttpContext.Request
  • Loading branch information
vegar authored and 304NotModified committed May 12, 2016
1 parent 63966e5 commit 6a1e79e
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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<HttpContextBase>();
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]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Text;
using NLog.Common;
#if !DNX
using System.Web;
#else
Expand Down Expand Up @@ -76,7 +77,7 @@ public class AspNetRequestValueLayoutRenderer : AspNetLayoutRendererBase
/// <param name="logEvent">Logging event.</param>
protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
var httpRequest = HttpContextAccessor.HttpContext.Request;
var httpRequest = HttpContextAccessor.HttpContext.TryGetRequest();
if (httpRequest == null)
{
return;
Expand Down Expand Up @@ -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
}

}

0 comments on commit 6a1e79e

Please sign in to comment.