Skip to content
This repository has been archived by the owner on Jan 24, 2021. It is now read-only.

Commit

Permalink
Don't allocate 4kB and Stream.CopyTo for empty bodies (#2898)
Browse files Browse the repository at this point in the history
  • Loading branch information
benaadams authored and khellang committed May 23, 2018
1 parent 3cef9e6 commit 68e0b9f
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions src/Nancy/Owin/NancyMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,11 @@ public static MidFunc UseNancy(NancyOptions options = null)

var url = CreateUrl(owinRequestHost, owinRequestScheme, owinRequestPathBase, owinRequestPath, owinRequestQueryString);

var nancyRequestStream = new RequestStream(owinRequestBody, ExpectedLength(owinRequestHeaders), StaticConfiguration.DisableRequestStreamSwitching ?? false);
var expectedLength = ExpectedLength(owinRequestHeaders);
// If length is 0 just use empty memory stream; as there is no body
var nancyRequestStream = (expectedLength == 0) ?
(Stream)new MemoryStream() :
new RequestStream(owinRequestBody, expectedLength ?? 0, StaticConfiguration.DisableRequestStreamSwitching ?? false);

var nancyRequest = new Request(
owinRequestMethod,
Expand Down Expand Up @@ -193,14 +197,24 @@ private static ClaimsPrincipal GetUser(IDictionary<string, object> environment)
return null;
}

private static long ExpectedLength(IDictionary<string, string[]> headers)
private static long? ExpectedLength(IDictionary<string, string[]> headers)
{
var header = GetHeader(headers, "Content-Length");

if (string.IsNullOrWhiteSpace(header))
return 0;
{
header = GetHeader(headers, "Transfer-Encoding");
if (string.IsNullOrWhiteSpace(header))
{
// No content-length or transfer-encoding means the length is definately 0
return 0;
}
// Has transfer-encoding, length is unknown
return null;
}

int contentLength;
return int.TryParse(header, NumberStyles.Any, CultureInfo.InvariantCulture, out contentLength) ? contentLength : 0;
// If length cannot be converted to an int, treat it as unknown
return int.TryParse(header, NumberStyles.Any, CultureInfo.InvariantCulture, out int contentLength) ? contentLength : (long?)null;
}

/// <summary>
Expand Down

0 comments on commit 68e0b9f

Please sign in to comment.