我有 3 个输出格式化程序,其中一个是我的自定义输出格式化程序,当 SupportedMediaType 是 Excel ( Content-type: application/vnd.ms-excel
) 时应该触发它。
services.AddControllers(options =>
{
options.OutputFormatters.Add(new ExcelOutputFormatter());; // Excel stylesheet XML
}).AddNewtonsoftJson().AddXmlSerializerFormatters();
但是,如果我的标题是 Accept: */*
,应用程序将我发送到 ExcelOutputFormatter。有没有办法让我默认使用 JSON 输出格式化程序而不是 Excel 格式化程序?
最佳答案
您需要模仿 AddNewtonsoftJson
使用的方法。和 AddXmlSerializerFormatters
,以便您可以将其链接在这两个之后;这相对简单:
services.AddControllers(options => {})
.AddNewtonsoftJson().AddXmlSerializerFormatters().AddExcelOutputFormatter();
// ...
public static IMvcBuilder AddExcelOutputFormatter(this IMvcBuilder builder)
{
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, ExcelOutputFormatterSetup>());
return builder;
}
class ExcelOutputFormatterSetup : IConfigureOptions<MvcOptions>
{
void IConfigureOptions<MvcOptions>.Configure(MvcOptions options)
{
options.OutputFormatters.Add(new ExcelOutputFormatter());
}
}
这应该使时间正确,以便您处于链条中的正确位置。附带说明:您可能还想添加到
options.FormatterMappings
.
关于c# - .NET Core 输出格式化程序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63299090/