c# - 无法修改响应标头,因为响应已经开始
问题描述
我正在使用 Asp.Net 核心 3.1
我已经实现了通过将数据写入 HttpContext Response 来下载 Excel/CSV 文件的功能,并且我能够下载该文件,但我收到错误日志说
[ERR] An unhandled exception has occurred while executing the request. (48a46595)
System.InvalidOperationException: The response headers cannot be modified because the response has already started.
此外,我在服务器上部署了我的应用程序并得到错误代码 502。
下面是代码。
public static class IWorkBookExtensions
{
public static void WriteExcelToResponse(this IWorkbook book, HttpContext httpContext, string templateName, ILogger<ExportDataController> _logger)
{
try
{
var response = httpContext.Response;
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
if (!string.IsNullOrEmpty(templateName))
{
var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
contentDisposition.SetHttpFileName(templateName);
response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
}
book.Write(response.Body);
}
catch(Exception ex)
{
_logger.LogError(ex.InnerException.ToString() + ex.Message);
}
}
}
下面是错误日志
2020-10-13T14:45:17.1452752-05:00 80003b-00-fc00-3f-84967bb [ERR] An unhandled exception has occurred while executing the request. (48a46595)
System.InvalidOperationException: The response headers cannot be modified because the response has already started.
at Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.ThrowIfReadOnly()
at Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.set_Item(String key, StringValues value)
at Microsoft.AspNetCore.Http.DefaultHttpResponse.set_ContentType(String value)
--- End of stack trace from previous location where exception was thrown ---
2020-10-13T14:45:17.1546662-05:00 80003b-00-fc00-3f-84967bb [WRN] The response has already started, the error page middleware will not be executed. (e1dd4c0d)
2020-10-13T14:45:17.2073595-05:00 880003b-00-fc00-3f-84967bb [ERR] Connection ID ""18300129210426"", Request ID ""80003b-00-fc00-3f-84967bb"": An unhandled exception was thrown by the application. (bf3147)
System.InvalidOperationException: The response headers cannot be modified because the response has already started.
解决方案
推荐阅读
- xml - 无法解组不受支持的类型
- r - R中的字符串-在字符串和数字之间插入所需/任意数字
- python - 在 Python 中创建一个类列表作为第二个类的属性
- razor - 如何在可重用 Razor 类库中的控制器中注入服务
- python - Python,Pandas 处理 df
- java - 如何将对象传递给 jButton1ActionPerformed
- java - 结合两种方法。int 不能被取消引用
- android - fitSystemWindows 与 windowTranlucentStatus 和 windowTranslucentNavigation 使工具栏太高
- swift - 谓词查找整数属性数组与集合的交集?
- javascript - 可以在 php 文件中调试 Javascript 吗?