【问题标题】:.net core 2.1 - AddJsonOptions not working.net core 2.1 - AddJsonOptions 不起作用
【发布时间】:2018-08-13 19:04:20
【问题描述】:

在我的 .net core 2.1 Web 应用程序(WebApi + SPA)中,我遇到了 API 无法正确处理 JSON 的问题:

  • 返回值不是驼峰式的
  • 我收到 JsonSerializationException:检测到属性的自引用循环错误

我的 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);
}

这确实解决了这两个问题 - 但我无法弄清楚为什么启动中的全局设置被忽略了。

【问题讨论】:

    标签: .net-core json.net


    【解决方案1】:

    这是因为序列化不是由框架完成的,而是由调用 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

    【讨论】:

    • 谢谢。有道理 - 如您在此处所述实施退货,您如何指定退货状态代码?我一直使用 IAction 结果,它可以让我轻松返回 OK 或 BadReqest 等。
    • 请检查 OkObjectResult 类。请参阅我的更新答案。
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 2020-02-02
    相关资源
    最近更新 更多