У меня была та же проблема на прошлой неделе, и я нашел альтернативное решение, используя мой собственный пользовательский форматер :
using CspReportLogger.Models;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
using System;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace CspReportLogger.Formatters
{
public class CSPReportInputFormatter : TextInputFormatter
{
public CSPReportInputFormatter()
{
// Specify the custom media type.
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/csp-report"));
SupportedEncodings.Add(Encoding.UTF8);
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding effectiveEncoding)
{
// Deserialize the body using our models and the JsonSerializer.
CspReportRequest report = await JsonSerializer.DeserializeAsync<CspReportRequest>(context.HttpContext.Request.Body);
return await InputFormatterResult.SuccessAsync(report);
}
}
}
Который должен быть зарегистрирован в Startup.cs, конечно:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options =>
{
options.InputFormatters.Insert(0, new CSPReportInputFormatter());
});
}
Я sh Я видел решение Кирка Ларкина ранее, поскольку оно, очевидно, является более кратким.
Я полагаю, что решение для пользовательского форматирования полезно, если вы хочу принять типы тел, которые не действительны json хотя.