Skip to content

Commit

Permalink
Make GetHeaderValue support HttpContext unavailable (#16654)
Browse files Browse the repository at this point in the history
* Make GetHeaderValue tolerant for when the http context is not available. Now it just returns null.

* Add unit tests
  • Loading branch information
bergmania authored Jun 25, 2024
1 parent e3d6596 commit 0afb4f7
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,5 @@ internal abstract class RequestHeaderHandler

protected RequestHeaderHandler(IHttpContextAccessor httpContextAccessor) => _httpContextAccessor = httpContextAccessor;

protected string? GetHeaderValue(string headerName)
{
HttpContext httpContext = _httpContextAccessor.HttpContext ??
throw new InvalidOperationException("Could not obtain an HTTP context");

return httpContext.Request.Headers[headerName];
}
protected string? GetHeaderValue(string headerName) => _httpContextAccessor.HttpContext?.Request.Headers[headerName];
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using Microsoft.AspNetCore.Http;
using Moq;
using NUnit.Framework;
using Umbraco.Cms.Api.Delivery.Services;

namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Cms.Api.Delivery.Services;

[TestFixture]
public class RequestHeaderHandlerTests
{
private const string HeaderName = "TestHeader";
[Test]
public void GetHeaderValue_return_null_when_http_context_is_unavailable()
{
IHttpContextAccessor httpContextAccessor = Mock.Of<IHttpContextAccessor>();

var sut = new TestRequestHeaderHandler(httpContextAccessor);

Assert.IsNull(sut.TestGetHeaderValue(HeaderName));
}

[Test]
public void GetHeaderValue_return_header_value_when_http_context_is_available()
{

const string headerValue = "TestValue";

HttpContext httpContext = new DefaultHttpContext();
httpContext.Request.Headers[HeaderName] = headerValue;

IHttpContextAccessor httpContextAccessor = Mock.Of<IHttpContextAccessor>();
Mock.Get(httpContextAccessor).Setup(x => x.HttpContext).Returns(httpContext);

var sut = new TestRequestHeaderHandler(httpContextAccessor);

Assert.AreEqual(headerValue, sut.TestGetHeaderValue(HeaderName));
}
}


internal class TestRequestHeaderHandler : RequestHeaderHandler
{
public TestRequestHeaderHandler(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
{
}

public string? TestGetHeaderValue(string headerName) => base.GetHeaderValue(headerName);
}

0 comments on commit 0afb4f7

Please sign in to comment.