How to fix 'IMvcBuilder' does not contain a definition for 'AddNewtonsoftJson'

By FoxLearn 6/21/2024 6:59:11 AM   224
The error message suggests that the IMvcBuilder interface doesn't have a method or extension method called AddNewtonsoftJson.

This method is typically used to configure JSON serialization settings in ASP.NET Core applications using Newtonsoft.Json instead of the built-in System.Text.Json.

Error CS1061 'IMvcBuilder' does not contain a definition for 'AddNewtonsoftJson' and no accessible extension method 'AddNewtonsoftJson' accepting a first argument of type 'IMvcBuilder' could be found (are you missing a using directive or an assembly reference?)

To resolve the addnewtonsoftjson not found, ensure you have added the necessary package reference in your project. You should have the Microsoft.AspNetCore.Mvc.NewtonsoftJson package installed.

To install the package Microsoft.AspNetCore.Mvc.NewtonsoftJson, you can right click on your project, then select Manage Nuget Packages => Install

Microsoft.AspNetCore.Mvc.NewtonsoftJson

If it's already installed, make sure you have imported the namespace Microsoft.Extensions.DependencyInjection where the extension method AddNewtonsoftJson is defined.

Finally, you can call as below.

// addnewtonsoftjson a not imvcbuilder
services.AddControllers().AddNewtonsoftJson();

Here's an example of how you would add NewtonsoftJson in your ASP.NET Core application during startup

// addnewtonsoftjson not imvcbuilder found
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers()
                .AddNewtonsoftJson(options =>
                {
                    // your settings...
                });
    }
}

After adding the package and configuring the JSON serialization, the AddNewtonsoftJson method should be recognized by the IMvcBuilder.