首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >即使在添加自定义OutputFormatters后仍保留默认输出格式

问即使在添加自定义OutputFormatters后仍保留默认输出格式
EN

Stack Overflow用户
提问于 2021-08-17 17:25:49
回答 1查看 27关注 0票数 0

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

代码语言:javascript
复制
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);
            }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2021-08-17 19:17:29

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

this post帮助我解决了这个问题,并按正确的顺序添加了输出格式化程序

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68821633

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档