如何在 Asp.net Core Web Api 中默认使用 Newtonsoft.Json? [英] How to use Newtonsoft.Json as default in Asp.net Core Web Api?

查看:27
本文介绍了如何在 Asp.net Core Web Api 中默认使用 Newtonsoft.Json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 ASP.Net Web Api Core 的新手.过去几年我一直在使用 ASP.Net MVC,我总是编写一个 ActionFilter 并使用 JSON.Net 进行 Serializing 数据转化为 JSON.因此,通过这种方式,我用 JSON.Net(据称是速度提高 400%).

如何在 ASP.Net Web Api Core 中完成所有这些工作?在哪里更改默认格式器?

注意:如果您有任何问题,请随时提问.

谢谢

解决方案

在 .NET Core 3.0+ 中包含 NuGet 包 Microsoft.AspNetCore.Mvc.NewtonsoftJson 然后替换

services.AddControllers();

ConfigureServices

services.AddControllers().AddNewtonsoftJson();

这是 .NET Core 3.0 中的预发布 NuGet 包,但 .NET Core 3.1 中的完整发布包.

我自己遇到过这个问题,但我发现this SO question and answer.

作为一个有用的更新:即使不安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson,调用 AddNewtonsoftJson() 的代码也能编译和运行 NuGet 包.如果这样做,它会在安装两个转换器的情况下运行,但默认使用 System.Text.Json 转换器,因为您正在阅读此答案,因此您可能不想要该转换器.因此,您必须记住安装 NuGet 包以使其正常工作(并且如果您清除并重做 NuGet 依赖项,请记住重新安装它).>

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 and used JSON.Net for Serializing data into JSON. So, in that way I replaced Microsoft's JavaScript Serializer (which is slower than JSON.Net) with JSON.Net (it is claimed to be 400% faster).

How to do all this in ASP.Net Web Api Core? Where to change the default formattor?

Note: Please feel free to ask if you have any questions.

Thanks

解决方案

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 your NuGet dependencies).

这篇关于如何在 Asp.net Core Web Api 中默认使用 Newtonsoft.Json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆