Click here to Skip to main content
15,885,278 members

Comments by Harisri (Top 1 by date)

Harisri 27-Apr-20 14:04pm View    
Hi, I could get your code refined and corrected a bit some what like this:

public class HttpRequestManager
{
private readonly IHttpClientFactory httpClientFactory;

public HttpRequestManager(IHttpClientFactory httpClientFactory)
{
this.httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
}

public async Task<string> GetJSONFromUrlAsync(string url, CancellationToken cancellationToken = default(CancellationToken))
{
string rawData = string.Empty;

using (var client = httpClientFactory.CreateClient())
{
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url))
{
using (var response = await client.SendAsync(request, cancellationToken))
{
response.EnsureSuccessStatusCode();
rawData = await response.Content.ReadAsStringAsync();
}
}
}
return rawData;
}
}

But when I have to call the method to return the data, I could not figure out how to instantiate the class you specified.

HttpRequestManager myHTTPManager = new HttpRequestManager((IHttpClientFactory)DefaultHttpClientFactory);
Task<string> jsonData = myHTTPManager.GetJSONFromUrlAsync(myUrl);

I mean how to pass arguments to the HttpRequestManager constructor. Can you please guide...