我已经在我的ASP.NET核心Web API中添加了几个用于CSV和Word文档的输出。从那时起,所有来自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);
}
}
}发布于 2021-08-17 19:17:29
我认为问题出在输出格式化程序的添加顺序上。默认值为JSOn和XML格式。在添加自定义格式化程序时,我们应该确保在输出格式化程序的末尾添加自定义格式化程序。
this post帮助我解决了这个问题,并按正确的顺序添加了输出格式化程序
https://stackoverflow.com/questions/68821633
复制相似问题