Response.AddHeader 附件文件和 AntiForgeryToken()

Response.AddHeader attachment file and AntiForgeryToken()

我正在处理 cshtml 文件,用户可以在其中将列表导出为 .xsl 文件。

像我所有其他观点一样,这个 cshtml 文件被我的 _Layout.cshtml 包围,其中包含直接在 nav-bar 中调用注销 built-in 函数我的应用程序,代码如下:

<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: 'Server cannot append header after HTTP headers have been sent.'

我没能正确理解问题。据我了解,Response.End() 函数发送我的 headers,但是 @Html.AntiForgeryToken() 函数尝试添加 headers 但不能,因为它们已经已发送,是吗?

所以我想我只需要删除 Response.End(),因为 headers 无论如何都会在我的页面加载时发送。此时,我没有收到任何错误,我的文件已正确下载。但它包含页面的所有 html 代码,而不仅仅是列表中的数据。

如何使文件可以使用 AntiForgeryToken() 系统下载?

我可以建议一个快速而好的选项,您可以跳过此特定操作的验证。 如何做到这一点可以在这里检查。