微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法修改响应标题,因为响应已经开始

如何解决无法修改响应标题,因为响应已经开始

我正在使用Asp.Net core 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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。