Created
December 11, 2015 15:53
-
-
Save anonymous/23a933502d44ec1c83fc to your computer and use it in GitHub Desktop.
Using Web API as a proxy for downloading files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public Task<HttpResponseMessage> Get() | |
{ | |
var resourceUrl = ".............."; | |
var range = ExtractRange(this.Request.Headers); | |
var request = new HttpRequestMessage(HttpMethod.Get, resourceUrl); | |
if (null != range) | |
request.Headers.Range = new RangeHeaderValue(range.From, range.To); | |
var client = new HttpClient(); | |
var response = client.SendAsync(request).ContinueWith<HttpResponseMessage>(t => { | |
var finalResp = new HttpResponseMessage(HttpStatusCode.OK); | |
finalResp.Content = t.Result.Content; | |
if (null != range) | |
finalResp.StatusCode = HttpStatusCode.PartialContent; | |
return finalResp; | |
}); | |
return response; | |
} | |
private static RangeHeaderValue ExtractRange(HttpRequestHeaders headers) | |
{ | |
if (null == headers) | |
throw new ArgumentNullException("headers"); | |
const int readStreamBufferSize = 1024 * 1024; | |
var hasRange = (null != headers.Range && headers.Range.Ranges.Any()); | |
var rangeHeader = hasRange ? headers.Range : new RangeHeaderValue(0, readStreamBufferSize); | |
if (!hasRange) | |
return rangeHeader; | |
// it is better to limit the request to a specific range in order to do no have an out-of-memory exception | |
var range = rangeHeader.Ranges.ElementAt(0); | |
var from = range.From.GetValueOrDefault(0); | |
rangeHeader = new RangeHeaderValue(@from, @from + range.To.GetValueOrDefault(readStreamBufferSize)); | |
return rangeHeader; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment