【发布时间】: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 代码编辑帖子