簡體   English   中英

Response.AddHeader附件文件和AntiForgeryToken()

[英]Response.AddHeader attachment file and AntiForgeryToken()

我正在處理一個cshtml文件,用戶可以在其中將列表導出為.xsl文件。

與其他所有視圖一樣,此cshtml文件被_Layout.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代碼,而不只是列表中的數據。

如何使用AntiForgeryToken()系統下載文件?

我可以建議您選擇一種快速且不錯的選擇,您可以跳過此特定操作的驗證。 可以在此處檢查操作方法。 忽略偽造令牌MVC

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM