【问题标题】:Keeping Default Output Formatters even after adding custom OutputFormatters即使在添加自定义 OutputFormatter 后仍保留默认输出格式化程序
【发布时间】:2021-08-18 03:17:29
【问题描述】:

我在我的 ASP.NET Core Web API 中添加了一些 CSV 和 Word Doc 的输出格式化程序。从那时起,来自 UI 的所有请求(具有Accept Header */*)都命中了 Outputformatters 代码。我知道定义自定义格式化程序会覆盖我的默认 JSON 格式化程序。我们如何保留默认行为以支持 JSON/XML 并仍然使用自定义格式化程序??

services.AddControllers(options =>
            {
                options.OutputFormatters.Add(new CSVOutputFormatter());
            });

   public class CSVOutputFormatter : OutputFormatter
        {
            public string ContentType { get; }
            public PDRDModels ViewModel { get; set; }
    
            public CSVOutputFormatter()
            {
                ContentType = "text/csv";
                SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(ContentType));
            }
    
            public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
            {
                var response = context.HttpContext.Response;
                var filePath = string.Format("xyz{0}.csv", DateTime.Now.Ticks);
                ViewModel = context.Object as model;
    
                using (var writer = new StreamWriter(filePath))
                using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
                {              

         /* Business Logic for populating csv */
                response.Headers.Add("Content-Disposition", "inline;filename=Pdrd.csv");
                response.ContentType = "text/csv";
    
                await response.SendFileAsync(filePath);
            }
    }
}

【问题讨论】:

  • 是什么让您认为它正在删除默认值?
  • 应该返回 JSON 的常规 API 调用不再起作用...每个 API 调用都通过 outputformatter
  • 那么CSVOutputFormatter 的内容是什么?例如,它是否接管了所有媒体类型?
  • 使用 CSVFormatter 代码编辑帖子

标签: c# .net-core


【解决方案1】:

我认为问题在于添加输出格式化程序的顺序。默认为 JSOn 和 XML 格式。添加自定义格式化程序时,我们应该确保将自定义格式化程序添加到输出格式化程序的末尾。

this 的帖子帮助我找出了问题并以正确的顺序添加了输出格式化程序

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 2014-02-15
    • 1970-01-01
    • 2022-09-25
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多