How to capture and log errors in program.cs with ASP.NET Core?
.NET Core version:ASP.NET Core 3.x
OS:windows server 2012 R2
I am getting an error on my website with Invalid non-ASCII or control character in header: 0x914. My website has URLs with non-ASCII characters.
my code in www.iaspnetcore.com:
Inspecting the std out logs for my site, I see exceptions like this:
It seems that when a redirect happens, the code in Microsoft.AspNetCore.Http.Internal.DefaultHttpResponse.Redirect is setting a Location header, which is probably one of these URLs with a non-ASCII character
Step 1: Add .CaptureStartupErrors(true) in program.cs
Please see CaptureStartupErrors and the method .CaptureStartupErrors(true) that will help you find error.
Here is my usual config for NetCore Web Apps:
Step 2: write ErrorLoggingMiddleware log error into Database
Step 3: change
return Redirect(returnUrl);
to
return Redirect(Uri.EscapeUriString(returnUrl));.