在我的.net core 2.1 Web应用程序(WebApi + SPA)中,我遇到API无法正确处理JSON的问题:
我的startup.cs> configureservices如下:
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("AppContext");
services.AddEntityFrameworkNpgsql().AddDbContext<AppContext>(options => options.UseNpgsql(connectionString));
services.AddScoped<ISCTMRepository, SCTMRepository>();
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
我尝试将控制器操作更新为以下内容:
[HttpGet, Route("")]
public async Task<IActionResult> GetLocations()
{
var _data = await _repo.GetLocations();
var json = JsonConvert.SerializeObject(_data,
new JsonSerializerSettings {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
return Ok(json);
}
这确实解决了这两个问题-但我无法弄清为什么忽略启动时的全局设置。
答案 0 :(得分:0)
这是因为序列化不是由框架完成的,而是由调用JsonConvert.SerializeObject
完成的,该调用不遵守您在Startup.cs中指定的配置-它确实尊重您的JsonSerializerSettings
作为参数传递。
如果这样编写API,则可以看到Startup.cs中的配置生效。
[HttpGet, Route("")]
public async Task<IActionResult> GetLocations()
{
var _data = await _repo.GetLocations();
return new OkObjectResult(_data); //Let the framework serialize this object
}
顺便说一句,ASP.NET Core默认情况下在序列化中使用驼峰式外壳,您实际上并不需要显式配置它。只需替换行JsonConvert.SerializeObject
。