Skip to content

Instantly share code, notes, and snippets.

@ErikAndreas
Last active October 30, 2017 11:57
Show Gist options
  • Save ErikAndreas/2362f2317a3757d72ba59a2231bc7b1e to your computer and use it in GitHub Desktop.
Save ErikAndreas/2362f2317a3757d72ba59a2231bc7b1e to your computer and use it in GitHub Desktop.
.net core static httpclient async send multiple requests with auth token
private static HttpClient client = new HttpClient();
// send off reqs as fast as possible, then process them, arbitrary Item's, each having a Url to process
public async Task<ActionResult> ProcessUrlList(List<Item> items, string token)
{
var reqs = new List<Task<HttpResponseMessage>>();
foreach(var item in items)
{
reqs.Add(Req(item.Url, token));
}
foreach(var req in reqs)
{
var resolved = await Resolve(req);
// process content of object returned from Resolve
}
return ProcessedContent; // psuedo
}
public Task<HttpResponseMessage> Req(string url, string token)
{
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url);
httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
return client.SendAsync(httpRequestMessage);
}
// return custom ResponseObject
public async Task<ResponseObject> Resolve(Task<HttpResponseMessage> responseMessage)
{
var response = await responseMessage;
using (var reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
{
var body = await reader.ReadToEndAsync();
// process body
}
// build custom ResponseObject ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment