asp.net IMvcBuilder AddJsonOptions在.Net Core 3.0中的位置?

az31mfrm  于 11个月前  发布在  .NET
关注(0)|答案(7)|浏览(137)

我刚刚将我的ASP web API项目从.NET Core 2.0升级到3.0。

services.AddMvc()
    .AddJsonOptions(opts => opts.SerializerSettings.ContractResolver 
        = new DefaultContractResolver());

字符串
确保序列化JSON的小写。
升级到3.0后,我得到这个错误:
错误CS1061“IMvcBuilder”不包含“AddJsonOptions”的定义,找不到接受类型“IMvcBuilder”的第一个参数的可访问扩展方法“AddJsonOptions”(是否缺少using指令或程序集引用?)
根据AddJsonOptions for MvcJsonOptions in Asp.Net Core 2.2,AddJsonOptions扩展方法是/曾经是由Microsoft.AspNetCore.Mvc.Formatters.Jsonnuget包提供的。我已经尝试安装/重新安装了这个,但仍然无法解析该方法。有趣的是,当我尝试添加using语句时,intellisense只显示Microsoft. AspNetCore. Mvc. Formatters. Xml,即使我添加了 Json nuget包。
有什么想法吗?AddJsonOptionsdocumentation只适用于.NET 2.2,所以也许该方法在3.0中已被弃用,而支持其他配置机制?

yvt65v4c

yvt65v4c1#

作为ASP.NET Core 3.0的一部分,团队默认不再包含Json.NET。你可以在announcement on breaking changes to Microsoft.AspNetCore.App中阅读更多关于Json.NET的信息。
与Json.NET不同,ASP.NET Core 3.0和.NET Core 3.0包含不同的JSON API,它更注重性能。您可以在announcement about “The future of JSON in .NET Core 3.0”中了解更多信息。
ASP.NET Core的新模板将不再与JSON.NET捆绑在一起,但您可以轻松地重新配置项目以使用它而不是新的JSON库。这对于与旧项目的兼容性非常重要,而且因为新库不应该是完整的替代品,所以您不会在那里看到完整的功能集。
为了使用Json.NET重新配置您的ASP.NET Core 3.0项目,您需要添加一个NuGet引用到Microsoft.AspNetCore.Mvc.NewtonsoftJson,这是一个包含所有必要位的包。然后,在Startup的ConfigureServices中,您需要像这样配置MVC:

services.AddControllers()
    .AddNewtonsoftJson();

字符串
这将设置MVC控制器并将其配置为使用Json.NET而不是新的API。除了控制器,您还可以使用不同的MVC重载(例如,用于具有视图或Razor页面的控制器)。该AddNewtonsoftJson方法具有一个重载,允许您配置Json.NET选项,就像您在ASP.NET Core 2.x中使用AddJsonOptions一样。

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

mspsb9vt

mspsb9vt2#

在使用.NET Core 3时,这对我很有效:

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

字符串

vbopmzt1

vbopmzt13#

确保安装了Microsoft.AspNetCore.Mvc.NewtonsoftJson包。


的数据

tjjdgumg

tjjdgumg4#

这对我来说是工作,从NuGet安装NewtonsoftJson包“dotnet添加包Microsoft.AspNetCore.Mvc.NewtonsoftJson --版本3.1.0”版本3.1.0为ASP.NET Core 3.0工作并使用以下代码-

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
    .AddNewtonsoftJson(opt => {
        opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    });

字符串
希望一切顺利,谢谢。

j8ag8udp

j8ag8udp5#

这将有助于尝试安装Nuget包
Microsoft.AspNetCore.Mvc.NewtonsoftJson

thtygnil

thtygnil6#

这将有助于

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddJsonOptions(options=> {  options.JsonSerializerOptions.PropertyNamingPolicy = null;
                 options.JsonSerializerOptions.DictionaryKeyPolicy = null;

            });

            services.AddDbContext<PaymentDetailContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
        }

字符串

a2mppw5e

a2mppw5e7#

这对我很有效,在使用.Net Core 3时:click here

相关问题