Allrameest
Allrameest

Reputation: 4492

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?

Upvotes: 7

Views: 2724

Answers (1)

Evk
Evk

Reputation: 101463

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("ÅÄÖ");
});

Upvotes: 13

Related Questions