使用Utf8Json作为Json序列化器来解决此问题。
在 ASP.NET Core 应用程序中,使用 Newtonsoft Json 序列化器序列化对象可能会引起奇怪的字符编码问题,这通常会导致意想不到的行为,例如在 API 响应中返回根据名称进行排序的对象。
解决此问题的方法之一是使用 Utf8Json 序列化器代替 Newtonsoft Json 序列化器。下面是一个简单的 ASP.NET Core 应用程序配置示例,其中在 ConfigureServices
方法中将 Utf8Json 注册为默认的 MVC JSON 序列化程序:
using Utf8Json.AspNetCoreMvcFormatter;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// 注册 Utf8Json 序列化程序作为 MVC JSON 序列化程序
services.AddMvc().AddMvcOptions(options =>
{
options.OutputFormatters.Clear();
options.OutputFormatters.Add(new Utf8JsonOutputFormatter());
});
}
}
这将使 Utf8Json 成为您 ASP.NET Core 应用程序的默认 JSON 序列化器,从而解决任何可能存在的字符编码问题。