c# - .NET Core 输出格式化程序顺序

标签 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();
但是,如果我的标题是 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/

相关文章:

c# - 查找两个字符串之间的所有子字符串

c# - 如何从两个与iOS和其他Unity平台兼容的列表中创建字典?

.net-core - 了解 Blazor 托管

c# - 错误返回 "No job functions found. Try making your job classes and methods public"后,尝试在 Linux 中构建 Azure 函数应用程序

c# - 未从 .NET MVC MultipartFormDataContent POST 收到 .NET Core API List<IFormFile> 文件

c# - 有没有办法使用 dbcontext 来包含()所有内容?

c# - Monodroid BitmapFactory.DecodeFileDescriptor 位图始终为 null

c# - 在 ASP.NET Core 中注册 HostedService 的正确方法。 AddHostedService 与 AddSingleton

asp.net-core - ASP.NET Core 2.1 中 [ApiController] 中的 POST 操作

asp.net-core - 在 Windows Server 上调用 ASP.NET Core 2.1 Web API 时出现 "500 - Internal server error"