JsonSerializerSettings and Asp.Net Core

我的梦境 提交于 2020-01-08 16:55:13

问题


Trying to set JsonOutputFormatter options:

var jsonFormatter = (JsonOutputFormatter) options.OutputFormatters.FirstOrDefault(f => f is JsonOutputFormatter);
if (jsonFormatter != null)
{
    jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}

or

mvcBuilder.AddJsonOptions(jsonOptions =>
    {
        jsonOptions.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    });

But as soon as I add this, I get:

MissingMethodException: Method not found: 'Newtonsoft.Json.JsonSerializerSettings Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter.get_SerializerSettings()'.

I'm using the standard Microsoft.AspNet.Mvc.Formatters.Json (6.0.0-rc1-final)

Edit: Solved it by installing Newtonsoft.Json 6.0.6 (which downgrades all other references)

Anyone got that already? Thanks..


回答1:


.Net Core 1.0 RTM comes with CamelCase formatting out-of-the-box. This is a behavior change from RC2. However, if you need to modify it, try this snippet:

services.AddMvc()
        .AddJsonOptions(opt =>
    {
        var resolver  = opt.SerializerSettings.ContractResolver;
        if (resolver != null)
        {
            var res = resolver as DefaultContractResolver;
            res.NamingStrategy = null;  // <<!-- this removes the camelcasing
        }
    });

More information here.

For dotnet core 1.0.1:

  services
            .AddMvcCore()
            .AddJsonFormatters(o => o...);



回答2:


I assume you are using ASP.Net Core and you should use "Microsoft.AspNetCore.Mvc":

So replace this:

"Microsoft.AspNet.Mvc": "6.0.0-rc1-final"

by this:

"Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final"


来源:https://stackoverflow.com/questions/35772387/jsonserializersettings-and-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!