c# - 如何在使用 AddNewtonsoftJson 时在 asp net core 3.1 mvc 中通过 DI(服务集合)检索 json 序列化程序设置

标签 c# asp.net-mvc asp.net-core json.net asp.net-core-3.1

我有一个使用 .netcore 3.1 的 ASP MVC 项目,我在其中覆盖序列化程序选项,如下所示

services
.AddControllers()
.AddNewtonsoftJson(options =>
{
    options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
    options.SerializerSettings.NullValueHandling = NullValueHandling.Include;
    options.SerializerSettings.Converters.Add(new StringEnumConverter
    {
        NamingStrategy = new CamelCaseNamingStrategy(),
    });
})

每当 MVC 为我序列化数据(请求/响应)时,这都可以正常工作。
但是现在,在其中一个中间件中,我需要手动序列化并返回一些数据作为响应,例如:

public async Task Invoke(HttpContext context)
{
    try
    {
        await _next(context);
    }
    catch (Exception exception)
    {
        ... // removed for simplicity
        await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse, _jsonSerializerSettings));
    }
}

在这里,我想重用现有设置进行序列化。但是旧的 MvcJsonOptions 在 .netcore 3.1 中不再可用(如果我错了,请更正)。
那么如何在不重复 json 序列化设置的情况下实现这一点呢?

最佳答案

Here I want to reuse existing settings for serialization.



由于您已经在 ConfigureServices() 方法中为 Mvc 配置了 NewtonsoftJson 选项,因此只需注入(inject) IOptions<MvcNewtonsoftJsonOptions>当你需要它的时候。例如,更改您的中间件以接受 IOptions<MvcNewtonsoftJsonOptions> 的参数。 :
public class MyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly JsonSerializerSettings _jsonSerializerSettings;

    public MyMiddleware(RequestDelegate next,IOptions<MvcNewtonsoftJsonOptions> jsonOptions)
    {
        // ... check null and throw
        this._next = next;
        this._jsonSerializerSettings = jsonOptions.Value.SerializerSettings;
    }

    public async Task Invoke(HttpContext context) 
    {
        try
        {
            await _next(context);
        }
        catch (Exception exception)
        {
            //... removed for simplicity
            await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse, _jsonSerializerSettings));
        }
    }
}

关于c# - 如何在使用 AddNewtonsoftJson 时在 asp net core 3.1 mvc 中通过 DI(服务集合)检索 json 序列化程序设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60168342/

相关文章:

c# - 方法中的泛型,c#

asp.net-mvc - ASP.Net MVC 路由无法正常工作

c# - 我可以为给定的 ActionResult 手动调用 ClaimsAuthorizationManager 吗?

c# - Asp.net core 为身份创建接口(interface)

asp.net-core - MVC 6 中缺少 AsyncController

c# - 使用参数指令时 T4 模板 NullReferenceException

c# - 子域作为查询字符串

c# - 基于子列表项创建 IGrouping

c# - 我可以将枚举传递给 Controller ​​以便模型绑定(bind)器绑定(bind)它吗?

asp.net-mvc - ASP.NET Core 3.0 Controller 路由不起作用