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

后端 未结 3 1397
予麋鹿
予麋鹿 2020-11-30 07:19

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 a

相关标签:
3条回答
  • 2020-11-30 08:08

    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.

    0 讨论(0)
  • 2020-11-30 08:09

    In .NET Core 3.0+ include the NuGet package Microsoft.AspNetCore.Mvc.NewtonsoftJson and then replace

    services.AddControllers();
    
    

    in ConfigureServices with

    services.AddControllers().AddNewtonsoftJson();
    
    

    This is a pre-release NuGet package in .NET Core 3.0 but a full release package in .NET Core 3.1.

    I came across this myself, but I've found that the same answer with some additional info is in this SO question and answer.

    Edit: As a useful update: code with the call to AddNewtonsoftJson() will compile and run even without installing the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package. If you do that, it runs with both converters installed, but defaulting to the System.Text.Json converter which you presumably don't want since you're reading this answer. So you must remember to install the NuGet package for this to work properly (and remember to re-install it if you ever clear down and redo you NuGet dependencies).

    0 讨论(0)
  • 2020-11-30 08:09

    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;
            });
    }
    
    0 讨论(0)
提交回复
热议问题