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)
我GetFileById在ASP.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 FileStreamResult与SqlReaderStream以下行连接:
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)
附加信息:
Get行动上.所有其他操作正常加载FilesController(其中,Get动作是)直接从继承Controller类
问题的可能原因是什么?
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)
我不会回来SqlReaderStream的FileStreamResult,因为流不是可搜索.我想这可能是一个问题.
尝试复制Streamto MemoryStream或byte数组并将其返回GetFileById.
此外,如果您在SqlReaderStream本地读取函数,则可以关闭与数据库的连接.
return File(byteArray, contentType, name);
Run Code Online (Sandbox Code Playgroud)
真正的问题是在这一行中:
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%,并且问题不会不再可重复。
| 归档时间: |
|
| 查看次数: |
1459 次 |
| 最近记录: |