Aut*_*zer 3 c# .net-core asp.net-core-webapi
我有 3 个输出格式化程序,其中之一是我的自定义输出格式化程序,当 SupportedMediaType 为 Excel ( Content-type: application/vnd.ms-excel)时应触发该格式化程序。
services.AddControllers(options =>
{
options.OutputFormatters.Add(new ExcelOutputFormatter());; // Excel stylesheet XML
}).AddNewtonsoftJson().AddXmlSerializerFormatters();
Run Code Online (Sandbox Code Playgroud)
但是,如果我的标题是Accept: */*,应用程序会将我发送到 ExcelOutputFormatter。有没有办法让我默认使用 JSON 输出格式化程序而不是 Excel 格式化程序?
您需要模仿AddNewtonsoftJsonand使用的方法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());
}
}
Run Code Online (Sandbox Code Playgroud)
这应该使时间正确,以便您处于链条中的正确位置。
附带说明:您可能还想添加到options.FormatterMappings.
| 归档时间: |
|
| 查看次数: |
218 次 |
| 最近记录: |