.net core读取appSetting.json文件中文字符乱码

.net core webapp 中添加一个appsetting.json文件如下:

{
  "message": "<b>hello你好啊</b>"
}

在Startup类,Configure方法中直接读取并打印到前端:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting(routes =>
            {
                routes.MapGet("/", async context =>
                {
                    var msg = Configuration["message"];
                    await context.Response.WriteAsync(msg);
                });
            });
        }

结果:

英文字符正常输出,中文乱码;

解决

在高级保存选项中,查看编码格式是否为utf-8 sign:

查看浏览器编码:firefox->右上角更多->文字编码:

手动设置Unicode后,正常输出中文字符:

看来是浏览器自动识别简体中文(gb2312?)导致,在字符打印之前设置响应头即可:

app.UseRouting(routes =>
            {
                routes.MapGet("/", async context =>
                {
                    var msg = Configuration["message"];
                    //指定响应头编码格式为utf-8
                    context.Response.ContentType = "text/plain; charset=utf-8";
                    await context.Response.WriteAsync(msg);
                });
            });

 

posted @ 2019-03-27 10:28  Zdelta  阅读(31)  评论(0编辑  收藏  举报