.NET Core 输出格式化程序顺序 [英] .NET Core Output formatters order

查看:27
本文介绍了.NET Core 输出格式化程序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个输出格式化程序,其中一个是我的自定义输出格式化程序,当 SupportedMediaType 为 Excel (Content-type: application/vnd.ms-excel) 时应该触发它.

I have 3 output formatters, one of which is my custom output formatter that should be triggered when SupportedMediaType is Excel (Content-type: application/vnd.ms-excel).

      services.AddControllers(options =>
      {
            options.OutputFormatters.Add(new ExcelOutputFormatter());; // Excel stylesheet XML
      }).AddNewtonsoftJson().AddXmlSerializerFormatters();

但是,如果我的标题是 Accept: */*,应用程序会将我发送到 ExcelOutputFormatter.有没有办法让我默认使用 JSON 输出格式化程序而不是 Excel 格式化程序?

However, if my header is Accept: */*, the application sends me to ExcelOutputFormatter. Is there a way for me to use the JSON output formatter instead of the Excel one by default?

推荐答案

您需要模仿 AddNewtonsoftJsonAddXmlSerializerFormatters 使用的方法,以便您可以链接它之后这两个;这个比较简单:

You would need to mimic the approach used by AddNewtonsoftJson and AddXmlSerializerFormatters, so that you can chain it after those two; this is relatively simple:

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());
    }
}

这应该使时间正确,以便您处于链条中的正确位置.

This should get the timing correct so that you're at the correct position in the chain.

附带说明:您可能还想添加到 options.FormatterMappings.

As a side note: you may also want to add to options.FormatterMappings.

这篇关于.NET Core 输出格式化程序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆