typically you would pass a HttpClient to the class constructor:
Class1 class1 = new Class1(httpclient);
if called from a controller, use the injected HttpClient.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I'm trying to Use IHttpClientFactory To Create HttpClient (ref: https://www.rahulpnath.com/blog/are-you-using-httpclient-in-the-right-way/).
At the end of the page, it says:
"The Controller class can now use the WeatherService and call it to get back the relevant data, as shown below."
What if we don't use Controller class but we want to use a class?, like:
Class1 class1 = new Class1();
How to inject the service and call the interface (in my case it's Task Get(string cityName);)
program.cs
services.AddHttpClient<IWeatherService,WeatherService>(c => {
c.BaseAddress = new Uri("http://api.weatherapi.com/v1/current.json");
});
builder.Services.AddSingleton<ITest, Test>();
builder.Services.AddHttpClient<ITest, Test>("test", c1 =>
{
c1.BaseAddress = new Uri("https://test.xxxxx.com/api");
c1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
c1.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue { NoCache = true };
c1.Timeout = TimeSpan.FromMinutes(3);
});
public interface IWeatherService
{
Task <string> Get(string cityName);
}
public class WeatherService: IWeatherService
{
private HttpClient _httpClient;
public WeatherService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task < string > Get(string cityName)
{
string APIURL = $ "?key={API_KEY}&q={cityName}";
var response = await _httpClient.GetAsync(APIURL);
return await response.Content.ReadAsStringAsync();
}
}
WeatherForecastController.cs
public WeatherForecastController(IWeatherService weatherService)
{
_weatherService = weatherService;
}
[HttpGet]
public async Task<string> Get(string cityName)
{
return await _weatherService.Get(cityName);
}
{
Task<string[]> RunAsync(object parameters);
}
public class Test : ITest
{
private readonly IHttpClientFactory _httpClientFactory = null!;
public Test(IHttpClienFactory httpClientFactory)
{
_httpClientFactory= httpClientFactory;
}
public async Task<string[]> RunAsync(object parameters)
{
object[] parameterArray = (object[])parameters;
string token = (string)parameterArray[0];
var tasks = new List<Task<string>>();
_httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Token", token);
bool _break = false;
do
{
await _httpClient.GetAsync(url).ContinueWith(async (c) =>
{
var response = await c;
if (response.IsSuccessStatusCode)
{
tasks.Add(response.Content.ReadAsStringAsync());
}
else
_break = true;
});
} while(_break=false);.
}
return await Task.FromResult(tasks)
}
}
typically you would pass a HttpClient to the class constructor:
Class1 class1 = new Class1(httpclient);
if called from a controller, use the injected HttpClient.