使用响应.传输文件下载文件,还包含了页面的源代码

本文关键字:包含 源代码 响应 传输 文件下载 文件 | 更新日期: 2023-09-27 18:18:25

下面是违规代码,我下载了一个csv文件,但是它将页面源代码附加到底部,关于如何防止这种情况的任何想法?

            var priceList = Test();
            const string downloadName = "PriceList.csv";
            var fs = new FileStream(downloadName, FileMode.Create);
            var csv = new CsvHelper.CsvHelper(fs);
            csv.Writer.WriteRecords(priceList);
            Response.ClearContent();
            //not sure what the correct content type is. This is probally wrong
            Response.ContentType = "application/xls";
            //Setting size is optional               
            Response.AddHeader("Content-Disposition",
               "attachment; filename=" + downloadName + "; size=" + fs.Length.ToString());
            var fn = fs.Name;
            fs.Close();
            loadingImage.Visible = false;
            Response.TransmitFile(fn);
            Response.Flush();

使用响应.传输文件下载文件,还包含了页面的源代码

Call Response.End() .

还有,为什么保存文件只是为了重新发送呢?这充其量是一种浪费,但如果您要重用该名称,那么如果两个人同时访问此页面,就会出现竞争条件。而不是发送文件,使用var csv = new CsvHelper.CsvHelper(Response.OutputStream),所以你直接写到浏览器(你必须先发送你的头)。

CSV文件的内容类型为text/csv

在刷新流或尝试强制下载后添加Response.End()方法

var priceList = Test();
        const string downloadName = "PriceList.csv";
        var fs = new FileStream(downloadName, FileMode.Create);
        var csv = new CsvHelper.CsvHelper(fs);
        csv.Writer.WriteRecords(priceList);
        Response.ClearContent();
        //not sure what the correct content type is. This is probally wrong
        Response.ContentType = "application/xls";
        //Setting size is optional               
        Response.AddHeader("Content-Disposition",
           "attachment; filename=" + downloadName + "; size=" + fs.Length.ToString());
        var fn = fs.Name;
        fs.Close();
        loadingImage.Visible = false;
        Response.TransmitFile(fn);
        Response.Flush();
        Response.End();