【发布时间】:2020-01-07 08:51:09
【问题描述】:
我正在处理一个 cshtml 文件,用户可以在其中将列表导出为 .xsl 文件。
像我所有其他视图一样,这个 cshtml 文件被我的 _Layout.cshtml 包围,其中包含直接在我的应用程序的导航栏中调用 LogOff 内置函数,代码如下:
<li>
@using (Html.BeginForm("LogOff", "Account"))
{
@Html.AntiForgeryToken()
<button type="submit"><i class="fa fa-power-off" aria-hidden="true"></i></button>
}
</li>
AntiForgeryToken 在这里是因为注销功能需要它。
为了使文件可下载,我使用了 Response.AddHeader 函数,如下所示:
public void ExportListFromTsv(List<FICHECONGE> data)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=FicheConges.xls");
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
Tools.WriteTsv(data, Response.Output);
Response.End();
}
Tools.WriteTsv() 函数如下:
public static void WriteTsv<T>(IEnumerable<T> data, TextWriter output)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
foreach (PropertyDescriptor prop in props)
{
output.Write(prop.DisplayName); // header
output.Write("\t");
}
output.WriteLine();
foreach (T item in data)
{
foreach (PropertyDescriptor prop in props)
{
output.Write(prop.Converter.ConvertToString(
prop.GetValue(item)));
output.Write("\t");
}
output.WriteLine();
}
}
正确生成并正确下载了 xls 文件,但之后我的应用程序尝试通过控制器在当前页面上重定向用户。我的问题是此时,我在@Html.AntiForgeryToken() 行加载_Layout.cshtml 时出错:
System.Web.HttpException: '服务器无法在发送 HTTP 标头后附加标头。'
我无法正确理解问题。据我了解,Response.End() 函数发送我的标头,但 @Html.AntiForgeryToken() 函数尝试添加标头并且不能因为它们已经发送,是这样吗?
所以我认为我只需要删除 Response.End(),因为无论如何标题都会在我的页面加载时发送。此时,我没有收到任何错误,并且我的文件已正确下载。但它包含页面的所有 html 代码,而不仅仅是 List 中的数据。
如何使用 AntiForgeryToken() 系统使文件可下载?
【问题讨论】:
标签: c# asp.net-mvc download xls antiforgerytoken