Make GetHeaderValue support HttpContext unavailable (#16654)

* Make GetHeaderValue tolerant for when the http context is not available. Now it just returns null.

* Add unit tests
This commit is contained in:
Bjarke Berg
2024-06-25 13:47:25 +02:00
committed by GitHub
parent e3d65967aa
commit 0afb4f7283
2 changed files with 49 additions and 7 deletions

View File

@@ -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];
}

View File

@@ -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);
}