我有NET5应用程序,在统计中,我已经将应用程序配置为使用Newtonsoft而不是System.Text.Json.发布CSP报告,我想添加application/csp-report作为支持的媒体类型。
尽管我已经配置使用AddNewtonsoftJson来使用Newtonsoft,但NewtonsoftJsonInputFormatter仍然不能作为输入格式化程序使用。当尝试在InputFormatters集合中查找时,下面的代码返回null。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(config =>
{
var jsonInputFormatter = options.InputFormatters
.OfType<NewtonsoftJsonInputFormatter>()
.First();
//jsonInputFormatter is null here
jsonInputFormatter.SupportedMediaTypes.Add("application/csp-report")
})
// Use Newtonsoft’s Json.NET instead of System.Text.Json.
.AddNewtonsoftJson((options)=>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
})
}发布于 2021-05-04 11:17:50
基于帖子here。那篇文章中被接受的答案对我不起作用。然而,另一个由@Vincent Rutten提出的建议工作确实有效
services.AddOptions<MvcOptions>()
.PostConfigure<IOptions<JsonOptions>, IOptions<MvcNewtonsoftJsonOptions>, ArrayPool<char>, ObjectPoolProvider, ILoggerFactory>(
(mvcOptions, jsonOpts, newtonJsonOpts, charPool, objectPoolProvider, loggerFactory) =>
{
var formatter = mvcOptions.InputFormatters.OfType<NewtonsoftJsonInputFormatter>().First(i => i.SupportedMediaTypes.Contains("application/json"));
formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/csp-report"));
mvcOptions.InputFormatters.RemoveType<NewtonsoftJsonInputFormatter>();
mvcOptions.InputFormatters.Add(formatter);
});https://stackoverflow.com/questions/67377799
复制相似问题