![](/img/trans.png)
[英]SQLDataLReader and CommandBehavior.SequentialAccess
[英]ASP.NET webapi HttpResponseMessage with ExecuteReaderAsync CommandBehavior.SequentialAccess
我需要通過WebApi從Sql Server傳輸blob數據。
我不想在Web服務器上緩沖內存中的blob數據。
我有以下代碼,但它不起作用 - 沒有例外。
public class AttachmentController : ApiController
{
public async Task<HttpResponseMessage> Get(int id)
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
await connection.OpenAsync();
using (var command = new SqlCommand("SELECT Content FROM [Attachments] WHERE ID = @ID", connection))
{
command.Parameters.AddWithValue("ID", id);
using (SqlDataReader reader = await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess))
{
if (await reader.ReadAsync())
{
using (Stream data = reader.GetStream(0))
{
var response = new HttpResponseMessage{Content = new StreamContent(data)};
//I get this from the DB else where
//response.Content.Headers.ContentType = new MediaTypeHeaderValue(attachment.ContentType);
//I get this from the DB else where
//response.Content.Headers.ContentLength = attachment.ContentLength;
return response;
}
}
}
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
}
Fiddle將以下錯誤寫為reposnse:[Fiddler] ReadResponse()失敗:服務器未返回此請求的響應。
如何將內容從數據庫流式傳輸到http輸出流,而不在內存中緩沖它?
在ASP.NET MVC完成讀取之前,您正在關閉流。 一旦你離開各種使用塊,它將在return
語句執行后立即關閉。
我知道沒有簡單的方法來實現這一目標。 最好的想法是編寫一個自定義的Stream
-derived類,它包裝ADO.NET返回的流,一旦流耗盡,就會處理所有內容( Stream
,reader,command和connection)。
此解決方案意味着您不能使用塊等。 我真的不喜歡它,但我現在想不出更好的東西。 這些要求很難組合:您需要流式傳輸行為並需要處理您打開的各種資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.