如何在使用 AddNewtonsoftJson 时通过 DI(服务集合)在 asp netcore 3.1 mvc 中检索 json 序列化器设置

sha*_*zak 5 c# asp.net-mvc json.net asp.net-core 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(),
    });
})
Run Code Online (Sandbox Code Playgroud)

每当 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));
    }
}
Run Code Online (Sandbox Code Playgroud)

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

itm*_*nus 7

在这里,我想重用现有的设置进行序列化。

由于您已在 ConfigureServices() 方法中为 Mvc 配置了 NewtonsoftJson 选项,因此只需IOptions<MvcNewtonsoftJsonOptions>在需要时注入 a 。例如,更改您的中间件以接受以下参数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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)