gpt4 book ai didi

c# - 从 ASP.NET Web Api 中的中间件访问 JsonOptions

转载 作者:行者123 更新时间:2023-12-04 14:08:53 25 4
gpt4 key购买 nike

在 ASP.NET Web API 项目中,我有一个自定义的 json 转换器。它在具有典型 API Controller 方法的场景中工作得非常好。但不知何故,我无法从在标准 Web API 管道之外工作的中间件访问配置的 JsonOptions。
一个简单的中间件来重现问题:

    public sealed class TestMiddleware
{
public async Task Invoke(HttpContext httpContext, IOptions<JsonOptions> jsonOptions)
{
// Some logic to check the middleware must be applied
// ...

// Return a response
await httpContext.Response.WriteAsJsonAsync(data, jsonOptions.Value.SerializerOptions);
}
}
和配置片段:
        public void ConfigureServices(IServiceCollection services)
{
services
.AddControllers()
.AddJsonOptions(configure =>
{
configure.JsonSerializerOptions.Converters.Add(new MyCustomConverter());
configure.JsonSerializerOptions.IgnoreNullValues = true;
});
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseMiddleware<TestMiddlewre>();
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
当 http 请求命中中间件时 IOptions<JsonOptions> jsonOptions有一个 SerializerOptions 对象,它不包含我在配置中设置的转换器。
有没有办法使用正确配置的 SerializerOptions 访问实际的 JsonOptions?

最佳答案

这个问题相当棘手。有两个命名空间包含 JsonOptions类(class):

  • Microsoft.AspNetCore.Mvc
  • Microsoft.AspNetCore.Http.Json

  • 使用第一个解决了我的问题。这两个类在内部非常相似,我在中间件实现过程中没有注意相应的命名空间。

    关于c# - 从 ASP.NET Web Api 中的中间件访问 JsonOptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66154525/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com