.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);
});
});

.NET Core Web应用程序在读取appSetting.json文件时遇到中文字符乱码问题。通过检查文件编码确保为UTF-8,并在浏览器中确认正确的文字编码。如果浏览器识别错误,可以通过设置响应头强制使用UTF-8来解决中文乱码。

7851

被折叠的 条评论
为什么被折叠?



