In my ASP.NET Core 2.1 application I tried to set a response header value that contains a non-ASCII character and got the following exception:
System.InvalidOperationException: Invalid non-ASCII or control character in header: 0x00E5 at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpHeaders.ThrowInvalidHeaderCharacter(Char ch) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpHeaders.ValidateHeaderCharacters(String headerCharacters) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpHeaders.ValidateHeaderCharacters(StringValues& headerValues) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpResponseHeaders.SetValueFast(String key, StringValues& value) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpHeaders.Microsoft.AspNetCore.Http.IHeaderDictionary.set_Item(String key, StringValues value)
OK, fair enough, I'm supposed to encode it - but how? If I call WebUtility.UrlEncode
on it that also encodes spaces and slashes, for example, which is obviously not what I want. What framework method am I supposed to call to do the encoding? (Or how do I just get ASP.NET Core to do this for me?)
Edit: It's not a duplicate of that question - I know that I cannot use non-ASCII characters, as it throws an exception! This question is about how to fix that, in ASP.NET Core.
Edit for context: I'm converting an existing application, which uses HttpListener in development and AWS Lambda via API Gateway in production. Both of those return non-ASCII characters just fine. I don't actually want to encode them at all, if I can avoid it, but there doesn't seem to be a way to get Kestrel to allow them.