Utf8/utf-16 return for webservice


#1

i grabbed the cli-samples and am looking at the HelloMvcApi. The problem I’m having is that the json is returned as UTF-16 as opposed to UTF-8 when I invoke the products api.

Is there a way to force UTF-8 instead of UTF-16? I appologize, I’m a dotnet core newbie, as I’ve been more a java developer in the past.

Here’s the api interaction http://pastebin.com/yGdKN4c9


#2

The log shows that the requester says in the Accept-Charset header that it supports various encodings, utf-16 and utf-8 among them.

If you don’t want to accept UTF-16, then the headers shouldn’t say that you do.


#3

Thanks! my solution was to change the client to send utf-8 header for
accept-charset, but my question was how to control this from the .net side
of things. My client did allow utf-8 (as you mention) and I wanted to
force that character encoding.


#4

You would get better and faster answers if you asked this in one of the ASP.NET Core repos, either aspnet/Home or aspnet/Mvc.

Anyway, as far as I can tell, the output encoding is decided by an output formatter (the logic for the default formatter is here). So, if you want to override this logic to always select UTF-8, no matter what Accept-Charset says, you can do that by creating your own JSON output formatter:

class ForcedUtf8JsonFormatter : JsonOutputFormatter
{
    public ForcedUtf8JsonFormatter(JsonSerializerSettings serializerSettings, ArrayPool<char> charPool)
        : base(serializerSettings, charPool)
    {
    }

    public override Encoding SelectCharacterEncoding(OutputFormatterWriteContext context)
        {
            return Encoding.UTF8;
        }
}

And then register it in Startup.ConfigureServices():

public void ConfigureServices(IServiceCollection services)
{ 
    services.AddMvcCore(options => options.OutputFormatters.Add(new ForcedUtf8JsonFormatter(new JsonSerializerSettings(), ArrayPool<char>.Shared)))
            .AddJsonFormatters();
}

(The values of the parameters in the formatter constructor are just my guesses, there might be a better way to get them.)


#5

You’re awesome, thanks Petr!


.NET Foundation Website | Blog | Projects | Code of Conduct