Allow setting the Content-Length header for a HTTP method HEAD (#951)

* Allow setting the Content-Length header for a HTTP method HEAD

* .
This commit is contained in:
Stef Heyenrath
2023-06-06 22:44:14 +02:00
committed by GitHub
parent 1f1bc05f00
commit adf1914877
2 changed files with 46 additions and 1 deletions

View File

@@ -5,12 +5,18 @@ using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Stef.Validation;
using WireMock.Constants;
using WireMock.Types;
namespace WireMock.Http;
internal static class HttpRequestMessageHelper
{
private static readonly IDictionary<string, bool> ContentLengthHeaderAllowed = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase)
{
{ HttpRequestMethod.HEAD, true }
};
internal static HttpRequestMessage Create(IRequestMessage requestMessage, string url)
{
Guard.NotNull(requestMessage);
@@ -50,7 +56,19 @@ internal static class HttpRequestMessageHelper
return httpRequestMessage;
}
var excludeHeaders = new List<string> { HttpKnownHeaderNames.Host, HttpKnownHeaderNames.ContentLength };
var excludeHeaders = new List<string> { HttpKnownHeaderNames.Host };
var contentLengthHeaderAllowed = ContentLengthHeaderAllowed.TryGetValue(requestMessage.Method, out var allowed) && allowed;
if (contentLengthHeaderAllowed)
{
// Set Content to empty ByteArray to be able to set the Content-Length on the content in case of a HEAD method.
httpRequestMessage.Content ??= new ByteArrayContent(EmptyArray<byte>.Value);
}
else
{
excludeHeaders.Add(HttpKnownHeaderNames.ContentLength);
}
if (contentType != null)
{
// Content-Type should be set on the content

View File

@@ -1,7 +1,9 @@
using NFluent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using WireMock.Http;
using WireMock.Models;
using WireMock.Types;
@@ -160,4 +162,29 @@ public class HttpRequestMessageHelperTests
// Assert
Check.That(message.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/xml; charset=Ascii");
}
[Theory]
[InlineData("HEAD", true)]
[InlineData("GET", false)]
[InlineData("PUT", false)]
[InlineData("POST", false)]
[InlineData("DELETE", false)]
[InlineData("TRACE", false)]
[InlineData("OPTIONS", false)]
[InlineData("CONNECT", false)]
[InlineData("PATCH", false)]
public void HttpRequestMessageHelper_Create_ContentLengthAllowedForMethod(string method, bool resultShouldBe)
{
// Arrange
var key = "Content-Length";
var value = 1234;
var headers = new Dictionary<string, string[]> { { key, new[] { "1234" } } };
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), method, ClientIp, null, headers);
// Act
var message = HttpRequestMessageHelper.Create(request, "http://url");
// Assert
message.Content?.Headers.ContentLength.Should().Be(resultShouldBe ? value : null);
}
}