我有一个使用 .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/