Skip to content

Instantly share code, notes, and snippets.

@mikeesouth
Created July 26, 2016 22:27
Show Gist options
  • Save mikeesouth/19f414366ab7d14e7ad5b093ef8f65f6 to your computer and use it in GitHub Desktop.
Save mikeesouth/19f414366ab7d14e7ad5b093ef8f65f6 to your computer and use it in GitHub Desktop.
/// <summary>
/// Downloads a blob file.
/// </summary>
/// <param name="blobId">The ID of the blob.</param>
/// <returns></returns>
public async Task<HttpResponseMessage> GetBlobDownload(int blobId)
{
// IMPORTANT: This must return HttpResponseMessage instead of IHttpActionResult
try
{
var result = await _service.DownloadBlob(blobId);
if (result == null)
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
// Reset the stream position; otherwise, download will not work
result.BlobStream.Position = 0;
// Create response message with blob stream as its content
var message = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(result.BlobStream)
};
// Set content headers
message.Content.Headers.ContentLength = result.BlobLength;
message.Content.Headers.ContentType = new MediaTypeHeaderValue(result.BlobContentType);
message.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = HttpUtility.UrlDecode(result.BlobFileName),
Size = result.BlobLength
};
return message;
}
catch (Exception ex)
{
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError,
Content = new StringContent(ex.Message)
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment