Search code examples
c#json.netasp.net-core-mvcasp.net-core-3.0.net-standard-2.1

'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0


I'm using netstandard2.1 library in my netcoreapp3.0 web application. When adding my service in Startup, I'm getting the below error:

'Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.0.0.0

I'm also using some features from Microsoft.AspNetCore.Mvc 2.2.0 package in my class library.

Here is my library .csproj,

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
  </ItemGroup>

</Project>

Here is my ServiceExtensions class from my library,

public static class ServiceExtensions
{
    public static IMvcBuilder AddMyLibrary(this IMvcBuilder builder)
    {
        builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        builder.AddJsonOptions(options =>
        {
            options.SerializerSettings.ContractResolver = new DefaultContractResolver();
        });
        builder.Services.ConfigureOptions<ConfigureLibraryOptions>();

        return builder;
    }
}

Here is my ConfigureLibraryOptions class,

public class ConfigureLibraryOptions : IConfigureOptions<MvcOptions>
{
    public void Configure(MvcOptions options)
    {
        options.ModelBinderProviders.Insert(0, new CustomBinderProvider());
    }
}

Here is the ConfigureServices from Startup,

services.AddControllersWithViews().AddMyLibrary();

Please help on why I'm getting this error and assist on how to solve this?


Solution

  • The reason why you're getting the error is because MvcJsonOptions was removed in .NET Core 3.0; you can read more about the breaking changes here.