Exceptionless icon indicating copy to clipboard operation
Exceptionless copied to clipboard

Throw exception: More bytes written than specified in the Content-Length header

Open ArvinHsieh opened this issue 6 years ago • 8 comments

Hi, I build the self-hosting, but the service keeps receiving error logs. What could be the problem?

Version: Exceptionless-7.0.1-pre13 Number of organizations: 13 Number of projects: 600+

ERROR LOG: 2020-11-12 10:39:45.313 +08:00 [ERR] HTTP GET /api/v2/projects/config?v=0 responded 500 in 1.1874 ms System.InvalidOperationException: More bytes written than specified in the Content-Length header. at Microsoft.AspNetCore.Server.HttpSys.ResponseBody.CheckWriteCount(Nullable`1 count) at Microsoft.AspNetCore.Server.HttpSys.ResponseBody.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) at Microsoft.AspNetCore.Server.HttpSys.ResponseStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) at System.IO.Pipelines.StreamPipeWriter.FlushAsyncInternal(CancellationToken cancellationToken) at Exceptionless.Web.Utility.ProjectConfigMiddleware.Invoke(HttpContext context) in C:\Localhost\Exceptionless-7.0.1-pre13\src\Exceptionless.Web\Utility\Handlers\ProjectConfigMiddleware.cs:line 62 at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.HttpOverrides.HttpMethodOverrideMiddleware.Invoke(HttpContext context) at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)

2020-11-12 10:39:45.320 +08:00 [ERR] ProcessRequestAsync System.InvalidOperationException: More bytes written than specified in the Content-Length header. at Microsoft.AspNetCore.Server.HttpSys.ResponseBody.CheckWriteCount(Nullable`1 count) at Microsoft.AspNetCore.Server.HttpSys.ResponseBody.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) at Microsoft.AspNetCore.Server.HttpSys.ResponseStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) at System.IO.Pipelines.StreamPipeWriter.FlushAsyncInternal(CancellationToken cancellationToken) at Exceptionless.Web.Utility.ProjectConfigMiddleware.Invoke(HttpContext context) in C:\Localhost\Exceptionless-7.0.1-pre13\src\Exceptionless.Web\Utility\Handlers\ProjectConfigMiddleware.cs:line 62 at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.HttpOverrides.HttpMethodOverrideMiddleware.Invoke(HttpContext context) at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext) at Exceptionless.Web.Startup.<>c__DisplayClass5_0.<b__1>d.MoveNext() in C:\Localhost\Exceptionless-7.0.1-pre13\src\Exceptionless.Web\Startup.cs:line 204 --- End of stack trace from previous location where exception was thrown --- at Joonasw.AspNetCore.SecurityHeaders.Csp.CspMiddleware.Invoke(HttpContext context) at Foundatio.Extensions.Hosting.Startup.WaitForStartupActionsBeforeServingRequestsMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Server.HttpSys.MessagePump.ProcessRequestAsync(Object requestContextObj) at Microsoft.AspNetCore.Server.HttpSys.MessagePump.ProcessRequestAsync(Object requestContextObj)

Thanks.

ArvinHsieh avatar Nov 12 '20 03:11 ArvinHsieh

Hello,

Can you try upgrading to the latest release which may resolve this issue (we'll also be cutting a release shortly with .NET 5.0 RTM support from the last rc). Also are you able to determine what the user agent of the client making this request?

niemyjski avatar Nov 12 '20 15:11 niemyjski

Hello,

Can you try upgrading to the latest release which may resolve this issue (we'll also be cutting a release shortly with .NET 5.0 RTM support from the last rc). Also are you able to determine what the user agent of the client making this request?

Thanks for your reply, I checked the code of Exceptionless-7.0.1-pre13 and the latest version of GITHUB, there is no difference in ProjectConfigMiddleware.cs. I try running to debug mode.

GET /api/v2/projects/config?v=0&access_token=XXXXXXXX Result: 2020-11-13 12:05:18.851 +08:00 [ERR] HTTP GET /api/v2/projects/config?v=0&access_token=XXXXXXXX responded 500 in 6135.7303 ms System.InvalidOperationException: More bytes written than specified in the Content-Length header.

But when I comment out "context.Response.ContentLength = json.Length;", I can respond normally. image

Is this an issue of unexpected Chinese char content length encode? I modify the response to bytes as follows.

string json = _serializer.SerializeToString(project.Configuration); byte[] jsonBytes = Encoding.UTF8.GetBytes(json); context.Response.StatusCode = StatusCodes.Status200OK; context.Response.ContentType = "application/json"; context.Response.ContentLength = jsonBytes.Length; await context.Response.Body.WriteAsync(jsonBytes);

It is working too.

ArvinHsieh avatar Nov 13 '20 04:11 ArvinHsieh

The latest release version is 7.0.7 and it contains .NET Core 5.0 RTM, the build you are on is a nightly build. It could very well be. Is there any chance you could add a unit test for this as well as put that data exclusion as a string here (non image)? Can you see if the latest version resolves this? I don't think it will after your last evidence but it's worth verifying. Is there a better way to set the content length that you know of?

niemyjski avatar Nov 13 '20 05:11 niemyjski

OK, I will try after upgrade my development environment, thank you.

ArvinHsieh avatar Nov 13 '20 05:11 ArvinHsieh

The latest release version is 7.0.7 and it contains .NET Core 5.0 RTM, the build you are on is a nightly build. It could very well be. Is there any chance you could add a unit test for this as well as put that data exclusion as a string here (non image)? Can you see if the latest version resolves this? I don't think it will after your last evidence but it's worth verifying. Is there a better way to set the content length that you know of?

Hi, I used version 7.0.7 for testing, but the same issue exists. I am not sure how to write a test case for Middleware, but I give two examples as follows.

https://github.com/exceptionless/Exceptionless/blob/cc472b1c8161d45dec0867de4d7f6f72de92ab82/src/Exceptionless.Web/Utility/Handlers/ProjectConfigMiddleware.cs#L57

// Contains Chinese
var jsonStr1 = "{\"version\":10,\"settings\":{\"@@UserAgentBotPatterns\":\"*bot*,*crawler*,*spider*,*aolbuild*,*teoma*,*yahoo*\",\"@@DataExclusions\":\"*unregistered*,*取得登入认证发生错误*,*This account unregistered!*\"}}";
context.Response.StatusCode = StatusCodes.Status200OK;
context.Response.ContentType = "application/json";
context.Response.ContentLength = jsonStr1.Length;
await context.Response.WriteAsync(jsonStr1); // Error: More bytes written than specified in the Content-Length header.

// Without Chinese
var jsonStr2 = "{\"version\":10,\"settings\":{\"@@UserAgentBotPatterns\":\"*bot*,*crawler*,*spider*,*aolbuild*,*teoma*,*yahoo*\",\"@@DataExclusions\":\"*unregistered*,*This account unregistered!*\"}}";
context.Response.StatusCode = StatusCodes.Status200OK;
context.Response.ContentType = "application/json";
context.Response.ContentLength = jsonStr2.Length;
await context.Response.WriteAsync(jsonStr2); // No exception

Because the project configuration may contain Chinese, maybe we should encode the content first.

byte[] jsonBtyes = Encoding.UTF8.GetBytes(_serializer.SerializeToString(project.Configuration));
context.Response.StatusCode = StatusCodes.Status200OK;
context.Response.ContentType = "application/json";
context.Response.ContentLength = jsonBtyes.Length;
await context.Response.Body.WriteAsync(jsonBtyes);

In order to be able to calculate the length correctly, do you have any suggestions? Thanks.

ArvinHsieh avatar Nov 13 '20 07:11 ArvinHsieh

I'm not sure, we will need todo some research on that. Would you mind looking into this and reporting your feedback. Can you check to see if the runtime will automatically set the content length for us? I'm wondering if we even need to set it.

niemyjski avatar Nov 13 '20 13:11 niemyjski

I checked the aspnetcore source code and found that encoding is used to calculate the length inside WriteAsync. https://github.com/dotnet/aspnetcore/blob/6de6ba907271a652e77c98a262e7ab6409c27930/src/Http/Http.Abstractions/src/Extensions/HttpResponseWritingExtensions.cs#L103

So when the final check is sent, the content-length of JSON string length will be inconsistent with the actual encoding length. https://github.com/dotnet/aspnetcore/blob/f490dd24c924e32acb46d0dee6b838237172d5e8/src/Servers/HttpSys/src/RequestProcessing/ResponseBody.cs#L511

I think there is no need to set the content-length, because asp.net core will respond to chunked. Thanks.

ArvinHsieh avatar Nov 16 '20 04:11 ArvinHsieh

Thanks again for bringing this to our attention and investigation! I just fixed this issue and added some test coverage for this. I also confirmed we don't need to set the length and it will be calculated (as talked about here https://weblog.west-wind.com/posts/2020/Mar/29/Content-Injection-with-Response-Rewriting-in-ASPNET-Core-3x). Please use a nightly ci build to confirm this is fixed for you. We will be pushing a release very soon.

niemyjski avatar Nov 16 '20 14:11 niemyjski