ASP.NET Core: Invalid non-ASCII or control character in header

I’m running some ASP.NET Core applications under Kestrel on Linux proxied by NGINX. I ran into an issue recently where I was getting the following exception when I redirected with certain strings:

System.InvalidOperationException: Invalid non-ASCII or control character in header: 0x00ED

The problem is that Kestrel does not support non-ASCII characters in the HTTP header, and I was redirecting when the string containing í, though many unicode characters would present similar problems. Here’s what a section of the problematic HTTP response looks like:

HTTP/1.1 302 Found
Location: /locations/juana-díaz
[Rest of the Response Here]

The solution is pretty simple: you need to encode strings that contain non-ASCII characters the same way you’d need to encode strings that contain any other characters with special meaning in a URL. The easiest thing to do is to use WebUtility.UrlEncode that’s in System.Net; for example:

using System.Net;
// ...
var encodedLocationName = WebUtility.UrlEncode(locationName);
return Redirect("~/locations/" + encodedLocationName);

Which will then produce a redirect that Kestrel is happier with, and looks something like this:

HTTP/1.1 302 Found
Location: /locations/juana-d%C3%ADaz
[Rest of the Response Here]