使用ASP.NET MVC在FileStreamResult中使用SqlDataReader时,请求未完成

Nik*_*tov 7 c# asp.net-mvc sqlconnection http filestream

出于性能考虑,我正在使用SqlConnection从SQL Server数据库SqlReaderStream返回一个byte[] :

private static SqlConnection GetConnection()
{
    var sqlConnectionStringBuilder =
        new SqlConnectionStringBuilder(
            ConfigurationManager.ConnectionStrings["StudentsSystemEntities"].ConnectionString)
            {
                Pooling = true
            };
    var connection = new SqlConnection(sqlConnectionStringBuilder.ConnectionString);
    connection.Open();
    return connection;
}

public FileDownloadModel GetFileById(Guid fileId)
{
    var connection = GetConnection();
    var command = new SqlCommand(
        @"SELECT [FileSize], [FileExtension], [Content] FROM [dbo].[Files] WHERE [FileId] = @fileId;",
        connection);
    var paramFilename = new SqlParameter(@"fileId", SqlDbType.UniqueIdentifier) { Value = fileId };
    command.Parameters.Add(paramFilename);

    var reader = command.ExecuteReader(
        CommandBehavior.SequentialAccess | CommandBehavior.SingleResult
        | CommandBehavior.SingleRow | CommandBehavior.CloseConnection);

    if (reader.Read() == false) return null;

    var file = new FileDownloadModel
                    {
                        FileSize = reader.GetInt32(0),
                        FileExtension = reader.GetString(1),
                        Content = new SqlReaderStream(reader, 2)
                    };
    return file;
}
Run Code Online (Sandbox Code Playgroud)

GetFileByIdASP.NET MVC操作中使用此方法:

[HttpGet]
public ActionResult Get(string id)
{
    // Validations omitted

    var file = this.filesRepository.GetFileById(guid);

    this.Response.Cache.SetCacheability(HttpCacheability.Public);
    this.Response.Cache.SetMaxAge(TimeSpan.FromDays(365));
    this.Response.Cache.SetSlidingExpiration(true);

    this.Response.AddHeader("Content-Length", file.FileSize.ToString());
    var contentType = MimeMapping.GetMimeMapping(
        string.Format("file.{0}", file.FileExtension));
    // this.Response.BufferOutput = false;
    return new FileStreamResult(file.Content, contentType);
}
Run Code Online (Sandbox Code Playgroud)

我将MVC FileStreamResultSqlReaderStream以下行连接:

return new FileStreamResult(file.Content, contentType);
Run Code Online (Sandbox Code Playgroud)

当我尝试使用Chrome(或Firefox ...)加载资源时,整个文件已加载但我收到以下错误:

注意:请求尚未完成!

注意:请求尚未完成!

响应标头:

HTTP/1.1 200 OK
Cache-Control: public, max-age=31536000
Content-Length: 33429
Content-Type: image/png
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcR---trimmed---G5n?=
X-Powered-By: ASP.NET
Date: Tue, 28 Jul 2015 13:02:55 GMT
Run Code Online (Sandbox Code Playgroud)

附加信息:

  • 我没有使用任何Chrome扩展程序
  • 问题只出在给定的Get行动上.所有其他操作正常加载
  • FilesController(其中,Get动作是)直接从继承Controller
  • 文件加载成功但浏览器仍在等待服务器: 在此输入图像描述
  • 我遇到与Firefox完全相同的问题

问题的可能原因是什么?

SqlReaderStream该类的源代码

public class SqlReaderStream : Stream
{
    private readonly int columnIndex;

    private SqlDataReader reader;

    private long position;

    public SqlReaderStream(
        SqlDataReader reader, 
        int columnIndex)
    {
        this.reader = reader;
        this.columnIndex = columnIndex;
    }

    public override long Position
    {
        get { return this.position; }
        set { throw new NotImplementedException(); }
    }

    public override bool CanRead
    {
        get { return true; }
    }

    public override bool CanSeek
    {
        get { return false; }
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override long Length
    {
        get { throw new NotImplementedException(); }
    }

    public override void Flush()
    {
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        var bytesRead = this.reader.GetBytes(
            this.columnIndex, this.position, buffer, offset, count);
        this.position += bytesRead;
        return (int)bytesRead;
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        throw new NotImplementedException();
    }

    public override void SetLength(long value)
    {
        throw new NotImplementedException();
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        throw new NotImplementedException();
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing && null != this.reader)
        {
            this.reader.Dispose();
            this.reader = null;
        }

        base.Dispose(disposing);
    }
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*bes 5

我不会回来SqlReaderStreamFileStreamResult,因为流不是可搜索.我想这可能是一个问题.

尝试复制Streamto MemoryStreambyte数组并将其返回GetFileById.

此外,如果您在SqlReaderStream本地读取函数,则可以关闭与数据库的连接.

return File(byteArray, contentType, name);
Run Code Online (Sandbox Code Playgroud)


Rom*_*nev 3

真正的问题是在这一行中:

this.Response.AddHeader("Content-Length", file.FileSize.ToString());
Run Code Online (Sandbox Code Playgroud)

您给出的文件大小错误,大于实际文件大小。这就是浏览器等待额外内容的原因。

要快速检查这确实是问题所在,请将行修改为以下内容

this.Response.AddHeader("Content-Length", (file.FileSize/10).ToString());
Run Code Online (Sandbox Code Playgroud)

这会将下载限制为相关文件的 1/10 - 但由于文件大小的偏差可能远小于一个数量级,因此文件将有足够的数据来提供所请求文件大小的 10%,并且问题不会不再可重复。