Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-ASCII characters scrambled when writing response in ASP.NET Core

If I put this Startup in an ASP.NET Core application the text will be scrambled (ÅÄÖ). Same thing happens if I do it in a middleware. Passing Encoding.UTF8 to WriteAsync doesn't help.

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Run(async context => { await context.Response.WriteAsync("ÅÄÖ"); });
    }
}

What's wrong and what can I do to fix it?

like image 679
Allrameest Avatar asked May 03 '18 10:05

Allrameest


1 Answers

You need to provide proper Content-Type header. Without it, browser is left guessing what content response represents, and in which encoding. And of course there is nothing wrong if that guess will be incorrect, like in your case.

app.Run(async context => {
    // text in UTF-8
    context.Response.ContentType = "text/plain; charset=utf-8";
    await context.Response.WriteAsync("ÅÄÖ");
});
like image 142
Evk Avatar answered Nov 15 '22 01:11

Evk