ASP.NET MVC FileContentResult SLOW

时间:2010-08-03 17:05:36

标签: asp.net-mvc string file-io stringbuilder filecontentresult

我们正在使用它来返回导出文件。当我们在很多记录上运行此导出时,运行需要将近10分钟。下面是代码的代码片段,它实际调用File()方法并返回结果。

Public Function Export(ByVal ID As Integer) As FileContentResult
  Dim str As String = String.Empty
  Dim data() As Byte
  Dim r As New ExportResult
  Dim Test As New TestConnection(WebUtil.UserToken)

  'This line is important coz IE download was prevented without this.
  ControllerContext.HttpContext.Response.ClearHeaders()

  r = Test.ExportFile(ID)
  data = Encoding.ASCII.GetBytes(r.ResponseString)

  Return File(data, "text/plain", r.DefaultFileName)

End Function

实际的ExportFile方法接受一个I​​D,调用另一个方法,它从数据库中获取一堆记录,对每一行执行一堆计算,然后创建一个StringBuilder,并为每一行填充StringBuilder然后在执行.ToString()之后将其弹出到List(Of String)中。然后此方法将List(Of String)返回到ExportFile方法,此方法创建另一个StringBuilder,从该列表追加所有字符串,将其转换为一个大字符串,并将其设置为结果的ResponseString属性('r '在上面的代码中。)

这就是它的工作原理。无论如何都要加快这个过程,比如很多?

-Scott

修改:更多代码

Public Function ExportFile(ByVal ID As Integer) As ExportResult
            Dim result As New ExportResult
            Dim s As New StringBuilder

            'Get all Records
            Dim dt As New DataTable
            Using dal As New SQL
                dal.Parameters.AddWithValue("@ID", ID)
                dal.Execute("[dbo].[uspGet]", dt)
                dal.Parameters.Clear()
            End Using

            Dim dataobj As New DataObj(dt, ID)

            'Create FileName
            If dt.Rows.Count > 0 Then
                Dim StartDate As DateTime = DateTime.Parse(dt.Rows(0).Item("StartDate"))
                Dim EndDate As DateTime = DateTime.Parse(dt.Rows(0).Item("EndDate"))
                result.DefaultFileName = String.Format("HMDA_{0}_{1}.dat", String.Format("{0:MMyyyy}", StartDate), String.Format("{0:MMyyyy}", EndDate))
            End If

            'Add Title Line
            s.AppendLine(dataobj.CreateTitleLine())

            'Add all Record Lines
            Dim records As List(Of String) = dataobj.CreateRecordLines()
            Dim last As Integer = records.Count - 1
            For i = 0 To last
                If i = last Then
                    s.Append(records(i))
                Else
                    s.AppendLine(records(i))
                End If
            Next

            result.ResponseString = s.ToString

            Return result
End Function

2 个答案:

答案 0 :(得分:1)

您的SQL效果如何?我会开始检查你的问题。

然后考虑你的文件有多大。数据仍然需要在客户端下载。

答案 1 :(得分:0)

避免多余的副本?也许你可以避免转换为字节和/或创建文件。只需将字符串写入响应即可,无需额外的工作。