2018-06-15 02:57:03 +02:00
|
|
|
using Microsoft.AspNetCore.Http;
|
2018-01-27 10:18:28 +01:00
|
|
|
using System;
|
2017-02-10 07:34:50 +01:00
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.IO;
|
|
|
|
using System.Linq;
|
|
|
|
using System.Text;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using System.Web;
|
|
|
|
|
|
|
|
namespace Teknik.Utilities
|
|
|
|
{
|
|
|
|
public static class ResponseHelper
|
|
|
|
{
|
2018-06-15 02:57:03 +02:00
|
|
|
public async static Task StreamToOutput(HttpResponse response, bool flush, Stream stream, int length, int chunkSize)
|
2017-02-10 07:34:50 +01:00
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
int processedBytes = 0;
|
|
|
|
byte[] buffer = new byte[chunkSize];
|
|
|
|
int bytesRemaining = length;
|
|
|
|
int bytesToRead = chunkSize;
|
|
|
|
do
|
|
|
|
{
|
|
|
|
if (chunkSize > bytesRemaining)
|
|
|
|
{
|
|
|
|
bytesToRead = bytesRemaining;
|
|
|
|
}
|
2017-04-09 09:16:24 +02:00
|
|
|
|
2017-02-10 07:34:50 +01:00
|
|
|
processedBytes = stream.Read(buffer, 0, bytesToRead);
|
|
|
|
if (processedBytes > 0)
|
|
|
|
{
|
2018-06-15 02:57:03 +02:00
|
|
|
await response.Body.WriteAsync(buffer, 0, processedBytes);
|
2017-04-09 09:16:24 +02:00
|
|
|
|
2018-01-29 00:08:32 +01:00
|
|
|
// Flush the response
|
|
|
|
if (flush)
|
|
|
|
{
|
2018-06-15 02:57:03 +02:00
|
|
|
await response.Body.FlushAsync();
|
2018-01-29 00:08:32 +01:00
|
|
|
}
|
|
|
|
|
2017-02-10 07:34:50 +01:00
|
|
|
// Clear the buffer
|
|
|
|
Array.Clear(buffer, 0, chunkSize);
|
2018-01-29 00:08:32 +01:00
|
|
|
|
|
|
|
// decrement the total bytes remaining to process
|
|
|
|
bytesRemaining -= processedBytes;
|
2017-02-10 07:34:50 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
while (processedBytes > 0 && bytesRemaining > 0);
|
|
|
|
}
|
2018-06-17 02:27:06 +02:00
|
|
|
catch (Exception)
|
2017-04-13 19:54:19 +02:00
|
|
|
{
|
|
|
|
// Don't worry about it. Just leave
|
2018-06-15 02:57:03 +02:00
|
|
|
await response.Body.FlushAsync();
|
2017-04-13 19:54:19 +02:00
|
|
|
}
|
2017-02-10 07:34:50 +01:00
|
|
|
finally
|
|
|
|
{
|
2018-06-15 02:57:03 +02:00
|
|
|
await response.Body.FlushAsync();
|
2017-02-10 07:34:50 +01:00
|
|
|
// dispose of file stream
|
2018-01-29 00:08:32 +01:00
|
|
|
stream?.Dispose();
|
2017-02-10 07:34:50 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|