Skip to content

Commit 58587b9

Browse files
author
Bart Koelman
committed
Fixed: return Content-Length header in HEAD response
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD
1 parent 4e3c5e8 commit 58587b9

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

src/JsonApiDotNetCore/Serialization/JsonApiWriter.cs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,12 @@ public async Task WriteAsync(object model, HttpContext httpContext)
6161

6262
string responseBody = GetResponseBody(model, httpContext);
6363

64+
if (httpContext.Request.Method == HttpMethod.Head.Method)
65+
{
66+
httpContext.Response.GetTypedHeaders().ContentLength = Encoding.UTF8.GetByteCount(responseBody);
67+
return;
68+
}
69+
6470
_traceWriter.LogMessage(() =>
6571
$"Sending {httpContext.Response.StatusCode} response for {httpContext.Request.Method} request at '{httpContext.Request.GetEncodedUrl()}' with body: <<{responseBody}>>");
6672

@@ -96,11 +102,6 @@ private string GetResponseBody(object model, HttpContext httpContext)
96102
return null;
97103
}
98104

99-
if (httpContext.Request.Method == HttpMethod.Head.Method)
100-
{
101-
return null;
102-
}
103-
104105
return responseBody;
105106
}
106107
#pragma warning disable AV1210 // Catch a specific exception instead of Exception, SystemException or ApplicationException

test/JsonApiDotNetCoreTests/IntegrationTests/Serialization/SerializationTests.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ await _testContext.RunOnDatabaseAsync(async dbContext =>
6565
// Assert
6666
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
6767

68+
httpResponse.Content.Headers.ContentLength.Should().BeGreaterThan(0);
69+
6870
responseDocument.Should().BeEmpty();
6971
}
7072

@@ -80,6 +82,8 @@ public async Task Returns_no_body_for_failed_HEAD_request()
8082
// Assert
8183
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
8284

85+
httpResponse.Content.Headers.ContentLength.Should().BeGreaterThan(0);
86+
8387
responseDocument.Should().BeEmpty();
8488
}
8589

0 commit comments

Comments
 (0)