How to use Newtonsoft.Json as default in Asp.net Core Web Api?

倾然丶 夕夏残阳落幕 提交于 2019-12-17 18:48:00

问题


I am new to ASP.Net Web Api Core. I have been using ASP.Net MVC for past few years and I always have written an ActionFilter and used JSON.Net for Serializing data into JSON. So, in that way I replaced Microsoft's JavaScript Serializer (which is slower than JSON.Net) with JSON.Net (it is claimed to be 400% faster).

How to do all this in ASP.Net Web Api Core? Where to change the default formattor?

Note: Please feel free to ask if you have any questions.

Thanks


回答1:


ASP.NET Core already uses JSON.NET as JavaScriptSerializer isn't implemented/ported to .NET Core.

Microsoft.AspNetCore.Mvc depends on Microsoft.AspNetCore.Formatter.Json which depends on Microsoft.AspNetCore.JsonPatch, which depends on Newtonsoft.Json (see source).

Update

This is only true for ASP.NET Core 1.0 to 2.2. ASP.NET Core 3.0 removes the dependency on JSON.NET and uses it's own JSON serializer.




回答2:


here is a code snippet to adjust the settings for a .net core application

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc()
        .AddJsonOptions(options => {
            // send back a ISO date
            var settings = options.SerializerSettings;
            settings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
            // dont mess with case of properties
            var resolver = options.SerializerSettings.ContractResolver as DefaultContractResolver;
            resolver.NamingStrategy = null;
        });
}


来源:https://stackoverflow.com/questions/42290811/how-to-use-newtonsoft-json-as-default-in-asp-net-core-web-api

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