aspnetcore: Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Unexpected end of request content.
We are facing intermittently BadHttpRequestException: Unexpected end of request content.
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException:
at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw (Microsoft.AspNetCore.Server.Kestrel.Core, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1ContentLengthMessageBody+<ReadAsyncInternal>d__9.MoveNext (Microsoft.AspNetCore.Server.Kestrel.Core, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream+<ReadAsyncInternal>d__30.MoveNext (Microsoft.AspNetCore.Server.Kestrel.Core, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream+<ReadAsync>d__36.MoveNext (Microsoft.AspNetCore.WebUtilities, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.WebUtilities.StreamHelperExtensions+<DrainAsync>d__3.MoveNext (Microsoft.AspNetCore.WebUtilities, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.Mvc.Formatters.NewtonsoftJsonInputFormatter+<ReadRequestBodyAsync>d__13.MoveNext (Microsoft.AspNetCore.Mvc.NewtonsoftJson, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder+<BindModelAsync>d__7.MoveNext (Microsoft.AspNetCore.Mvc.Core, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder+<BindModelAsync>d__7.MoveNext (Microsoft.AspNetCore.Mvc.Core, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider+<>c__DisplayClass0_0+<<CreateBinderDelegate>g__Bind|0>d.MoveNext (Microsoft.AspNetCore.Mvc.Core, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker+<<InvokeInnerFilterAsync>g__Awaited|13_0>d.MoveNext (Microsoft.AspNetCore.Mvc.Core, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker+<<InvokeNextResourceFilter>g__Awaited|24_0>d.MoveNext (Microsoft.AspNetCore.Mvc.Core, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow (Microsoft.AspNetCore.Mvc.Core, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next (Microsoft.AspNetCore.Mvc.Core, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync (Microsoft.AspNetCore.Mvc.Core, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker+<<InvokeAsync>g__Logged|17_1>d.MoveNext (Microsoft.AspNetCore.Mvc.Core, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.Routing.EndpointMiddleware+<<Invoke>g__AwaitRequestTask|6_0>d.MoveNext (Microsoft.AspNetCore.Routing, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware+<Invoke>d__5.MoveNext (Microsoft.AspNetCore.Authorization.Policy, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+<Invoke>d__6.MoveNext (Microsoft.AspNetCore.Authentication, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol+<ProcessRequests>d__214`1.MoveNext (Microsoft.AspNetCore.Server.Kestrel.Core, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
We are running on .NET Core 3.1.5, this exception seemed to only appear when we moved over to .NET Core 3.0
There have been similiar issues opened in the past, https://github.com/dotnet/aspnetcore/issues/19476#issuecomment-629457165 and https://github.com/dotnet/aspnetcore/issues/6575.
This exception seems to be thrown when a client aborts mid-request. My question is, should this be logged as a warning instead of an exception? It creates a lot of noise in our logs.
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Reactions: 42
- Comments: 89 (22 by maintainers)
We are facing the same issue on .NET 6 Preview 7:
I can confirm that it is still happening in .NET 8.
The issue is still here in 5.0, version 2.2 is normal.
Yes
We’ve moved this issue to the Backlog milestone. This means that it is not going to be worked on for the coming release. We will reassess the backlog following the current release and consider this item at that time. To learn more about our issue management process and to have better expectation regarding different types of issues you can read our Triage Process.
I’ve just opened a PR (https://github.com/dotnet/aspnetcore/pull/60359) to solve this issue in a safe way that’s fairly straightforward. Basically we can skip logging these bad requests as an application error and continue to allow people who want to see it to opt into bad request logging.
This is by design. BadHttpRequestException is an IOException. The request is ‘bad’ because it’s being closed by the client before we receive the entire request body. Model binding can’t complete.
The proposed fix in this issue is that BodyModelBinder should catch IOExceptions and terminate processing.
@adityamandaleeka 5 days have past since my last offer of help, but unfortunately I have been NOT contacted by you to provide the sample project to reproduce the bug, so that it can be fixed. This bug has been open for 4.5 years. Does Microsoft even care about the developers? Or considering the situation of Windows 11’s “problematic” updates, does MS care about its end-users?
I have mentioned this bug, 6-7 months ago, and in the meanwhile, I have learned “Java”, and you know what? I’m not looking back. MS is loosing simply developers and end-users because of lack of support, which will eventually cost MS money.
I’m avoiding .NET Core like plague. In my projects, I’m using either “outdated” .NET Framework or Java, but no .NET Core, because of bugs and lack of support.
Developers and end-users are starting to get “angry” with MS. Before spending 80 billion dollars on AI, first fix Windows 11, then fix .NET Core and your development platforms.
Experiencing the same issue with my .NET 6.0, .NET 7.0, and .NET 8.0 apps. Surprisingly, this only happens when the apps are under load. Any resolution or workaround would be super helpful. Thank you.
Same here. Only happens under heavy load. We are using .NET 6. Don’t really know how to solve it and this is a serious production problem.
I’m using Bombardier for high load testing. I noticed the output starts printing BadHttpRequestException when connection count is more than 25+. So around 50 concurrent connections I’m constantly getting this exception, which later actually stops the server from responding, even when I abort the Bombardier test. The log output keeps throwing the error minutes after I stop the test. The only solution then is to restart.
Feels like thread starvation but I’m not sure how to approach it.
All my code is fully async, even when this is happening, the CPU and Memory are very low. The function I’m testing is performing some Cosmos DB queries (Read/write) and so on.
@supermihi , sorry for missing this message, you can do what as @deleteLater proposed. For our project, we use a custom exception handler middleware to ignore the
BadRequestExceptionIt would be good to at least throw more meaningful exception/message – we could all see the same final exception, but the reason for it being thrown could be different (I see this being single user on a local machine, so I very doubt it is a load issue in my case).
I did a wireshark capture to confirm my theory.
In this scenario, I modified your sample to use 400 concurrent connections for a 10 second warmup period, then back off to 40 concurrent connections for the actual test.
We can see that there are a series of
RST, ACKpackets right around the 10 second mark, which indicate that the client has forcefully closed the connection. The Win=0 thing means the client isn’t willing to receive any more data at this point.Notably, after this set of
BadHttpRequestExceptions, the rest of the test (the post-warmup period from the autocannon perspective) went fine, indicating there’s no lasting effects on the Kestrel side.Does anyone know if it’s still happening in .NET 8?
Have the same issue with
dotnet-isolatedAzure Function on Linux in B1 plan .NET 7. Its really annoying because my function receives houndreds of POST requests each seconds and i have a lot of those exceptions:Can i just omit that exceptions @Tratcher ?
💡💡 Now that I’ve been able to narrow the search space, I’ve verified that the problem (at least in my case) is due to a client calling an API (with HttpPost) and canceling it almost immediately (closing the connection). My guess is that in some cases, the framework, instead of correctly throwing an OperationCanceledException, tries to read the body, fails (perhaps because the body was not transmitted yet or because the connection was closed) and incorrectly throws BadHttpRequestException.
💡 In some experiments I am doing, I have just noted that each time this exception is thrown, ((Microsoft.AspNetCore.Http.DefaultHttpContext)context).HttpContext).RequestAborted is in cancelled state (IsCancellationRequested is true). It seems (at least in my case) that sometimes when the client closes the connection, somewhere in the asp.net core pipeline, this BadHttpRequestException is thrown instead of OperationCanceledException.
@adityamandaleeka It seems that this issue is introduced long ago in this PR: https://github.com/dotnet/aspnetcore/pull/16725 with this change: https://github.com/dotnet/aspnetcore/commit/e3b971a75e2512d267605aa190122b874d9d948d#diff-6724c4b674672fff80410c379bdc2b86ee5e6b797ef797cbf667a80877113d7cR94
I feel we should replace “ThrowUnexpectedEndOfRequestContent()” with just “break;” on this line, as client has canceled the request, so we can break gracefully: https://github.com/dotnet/aspnetcore/blob/a4ca93128fcc08c1c8927cf6c63bd501ee656193/src/Servers/Kestrel/Core/src/Internal/Http/Http1ContentLengthMessageBody.cs#L91
In that case, this sounds like some kind of expected behaviour. If that is the case, does it make sense to reduce the log level of this to Warning or Info? It is not an application error.
By the way, for anyone that experienced the same problem, here is what I found. So we are running a pod with dotnet 8 using the official Microsoft image
mcr.microsoft.com/dotnet/sdk:8.0. The pod we had is a dotnet REST API that does a lot of HTTP calls to other services. It’s kind of a proxy to be honest.I tried to contact API enpoints that do not make any HTTP calls, and the server returned a response immediately, so I knew that the problem was occurring when the server was making HTTP calls to other services.
I tried to take a look by downloading netstat into the pod and realized that the problem was socket starvation. In summary, we were using a deprecated API that Dotnet recommended avoiding. (WebClient).
The solution for us was to do a migration and replace all those calls with the recommended API (HTTPClient). Furthermore, you should avoid using that class once per request, as it can also cause socket starvation. It is meant to be used as a singleton or using the HttpClientFactory with DI.
I hope this helps some of you that are dealing with the issue.
It’s still relevant! ASP.Net 7
We have been looking into this issue a bit more, and found out that what is contributing to the exception was a couple of blocking calls in our api. So here is what we did
Ben.BlockingDetectorin our apiKestrel.Core.Internal.Http.HttpRequestStream.ReadyAsyncInternalIn summary, I don’t think ignoring the exception as recommended may be the right thing to do here since, even though not direct, the exception tells us we have some blocking issue that needs to be looked at.
You only need to tune the minimum threads if you have LOTS of blocking.
use mvc-exception-filter or a global exception middleware, then check and ignore
@WeihanLi could you share a code snippet for filtering that exception?
I add a custom exception handler to ignore the
BadHttpRequestExceptionThanks for contacting us. We’re moving this issue to the
Next sprint planningmilestone for future evaluation / consideration. We will evaluate the request when we will planning the work for the next milestone. To learn more about what to expect next and how this issue will be handled you can read more about our triage process here.@adityamandaleeka I have created a public GitHub repo for you with very simplified codes https://github.com/taylaninan/WebAPICore8-BadHttpRequest
Just concentrate on the file “Program.cs”, which is only 129 lines long in total. The public repo has a folder named “Autocannon” for load-testing and reproducing the “BadHttpRequest” exception.
Just open the project in Visual Studio 2022 and hit “run” to start the Kestrel server.
For autocannon to work, you must have installed “node & npm” on your computer. Then just install autocannon with “npm install autocannon” to your computer. After that start the autocannon test script (“autocannon-tests.bat”). You will see a lot of “BadHttpRequest” errors on the Console/Terminal.
If you have any questions, don’t hesitate to ask me for help…
It is actionable right away, and it was from the beginning. If you use “pretty generic exception” then it is pure common sense to actually include the reason of the problem (as the message), so we (end-developers) at least understand what is going on.
Reproducing is tricky if it happens say once in 10 000 times, but once it hits we are not left in dark at least.
I experience the same issue on .NET 7.0, and I also have the global exception handler middleware but this not helping me 😛
Any update on this. We started seeing this immediately after upgrading to
.NET 6from.NET 3.1.Thanks for contacting us. We’re moving this issue to the
.NET 8 Planningmilestone for future evaluation / consideration. Because it’s not immediately obvious that this is a bug in our framework, we would like to keep this around to collect more feedback, which can later help us determine the impact of it. We will re-evaluate this issue, during our next planning meeting(s). If we later determine, that the issue has no community involvement, or it’s very rare and low-impact issue, we will close it - so that the team can focus on more important and high impact issues. To learn more about what to expect next and how this issue will be handled you can read more about our triage process here.Well I did check each and every line of code in this specific method - it seems there’s no blocking calls. Also used Ben.BlockingDetector to make sure I didn’t miss anything. Raising the min threads minimized the amount of errors but I still get them at times (heavy load). In our case it is also an API for a mobile app.
I’ve hit the same case, however it is not specifically ‘high’ load but the ‘slow’ networks that mostly caused this.
We have mobile apps connecting to our services, these devices do not always have the fastest networks. When uploading things like images / videos / … these requests can take a long time to arrive.
Example: On iOS we use NSUrlSessions background which (to my best understanding) optimises for battery & network usage. So chucks of bytes arrive ‘slowly’, sometimes with 10+ seconds delay between chunks. (multiple concurrent uploads on a 3G/edge networks are not the fastest)
Do note that for us, around 80-90% of the requests complete in less than 10sec, with data arriving at an ‘acceptable’ rate for kestrel. It is to accommodate those requests under poor network conditions to still complete that we had to add:
Now, we also use Azure Blob Storage for storing these. Basically we do something like this:
Now at this stage we had a lot of ‘BadRequestExceptions’ until we raised the ‘ThreadPool MinThread’.
To my best understanding, we have ‘at least’ 2 async operations per request here that (might) take a long time to complete. So this might be the cause for ‘threadpool starvation’ in our case.
As we run on kubernetes, and these applications share nodes, we are currently unsure if/how this would affect other applications running on the same nodes. And if we should maybe just scale up the number of ‘pods’ these application run under to accommodate for those slow request, while leaving threadpool defaults as they are
For us is happening in high load for all services that are using following code:
var reader = new StreamReader(Request.Body, Encoding.UTF8); string payload = await reader.ReadToEndAsync();Note: timeout is long enough, so connection is not closed.
We were also seeing this issue intermittently in .NET5 and .NET6 (didn’t try in previous versions). Tweaking the thread pool seems to have “fixed” it: ThreadPool.SetMaxThreads(32_767, 2_000); ThreadPool.SetMinThreads(1_000, 1_000);
Thanks for contacting us. We’re moving this issue to the
.NET 7 Planningmilestone for future evaluation / consideration. Because it’s not immediately obvious that this is a bug in our framework, we would like to keep this around to collect more feedback, which can later help us determine the impact of it. We will re-evaluate this issue, during our next planning meeting(s). If we later determine, that the issue has no community involvement, or it’s very rare and low-impact issue, we will close it - so that the team can focus on more important and high impact issues. To learn more about what to expect next and how this issue will be handled you can read more about our triage process here.The issue is still here in 5.0.7
The exception needs to be thrown from the request body APIs so you don’t think the request finished gracefully, but the caller should catch it. In this case that’s MVC, and I think they’re adding something in 5.0.