我有一个使用的 ASP.NET Core 3.1 应用程序
services.AddControllers().AddNewtonsoftJson();
使用 Newtonsoft JSON 序列化器。不幸的是我无法一步完全切换到
System.Text.Json
。
有没有办法放置像这样的属性
[NewtonsoftJson]
public class MyController : Controller
{
// ...
在那些我还无法迁移的控制器上——并且仅对这些控制器使用 Newtonsoft?
根据您的描述,我建议您可以考虑使用ActionFilterAttribute来实现您的要求。
如下:
public class NewtonsoftJsonFormatterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
if (context.Result is ObjectResult objectResult)
{
var jsonOptions = context.HttpContext.RequestServices.GetService<IOptions<MvcNewtonsoftJsonOptions>>();
objectResult.Formatters.RemoveType<SystemTextJsonOutputFormatter>();
objectResult.Formatters.Add(new NewtonsoftJsonOutputFormatter(
jsonOptions.Value.SerializerSettings,
context.HttpContext.RequestServices.GetRequiredService<ArrayPool<char>>(),
context.HttpContext.RequestServices.GetRequiredService<IOptions<MvcOptions>>().Value));
}
else
{
base.OnActionExecuted(context);
}
}
}
更多详情,可以参考这篇文章。