本文主要介绍.NET Core 2.0 升级 3.0,调用AddJsonOptions(options =>options.SerializerSettings.ContractResolver = new DefaultContractResolver());报措问题(Error CS1061 'IMvcBuilder' does not contain a definition for 'AddJsonOptions' and no accessible extension method 'AddJsonOptions' accepting a first argument of type 'IMvcBuilder' could be found (are you missing a using directive or an assembly reference?),以及在.NET Core 3.0配置JSON的方法。

使用AddJsonOptions出错原因

ASP.NET Core 3.0中默认情况下不再包括Json.NET。代替Json.NET,ASP.NET Core 3.0和.NET Core 3.0包括一个不同的JSON API,该API更加注重性能。ASP.NET Core的新模板将不再与Json.NET捆绑在一起,但您可以轻松地重新配置项目,以使用它而不是新的JSON库。这对于与较旧项目的兼容性,以及对新库都不应完全替代都非常重要。

配置解决方法

要使用Json.NET重新配置ASP.NET Core 3.0项目,将需要添加NuGet引用Microsoft.AspNetCore.Mvc.NewtonsoftJson,该引用是包含所有必要的软件包。然后,在Startup的中ConfigureServices,将需要像这样配置MVC:

services.AddControllers()
.AddNewtonsoftJson();

或者

services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});

除了上述方法,也可以尝试如下配置:

services.AddMvc().AddJsonOptions(o =>
{
o.JsonSerializerOptions.PropertyNamingPolicy = null;
o.JsonSerializerOptions.DictionaryKeyPolicy = null;
});



推荐文档