in .razor file I use
@inject HttpClient Http
to get access to the HTTPClient.
Is there a way to do the same in a .cs file or do I have to pass it along as a parameter?
update
I thought I had it, but I don't.
Using statements
using System.Net.Http;
using Microsoft.AspNetCore.Components;
using System.Net.Http.Json;
defined as class parameter
[Inject]
protected HttpClient Http {get;set;}
in my call Task
await Http.GetFromJsonAsync<SharedGLAccount[]>($"api/{ST_comp}/GLAccounts")
getting the following error
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Value cannot be null. (Parameter 'client')
I suggest you use IHttpClientFactory
for this. Checkout this documentation which explains the benefits of using this and also copied below:
- Provides a central location for naming and configuring logical
HttpClient
instances. For example, a client named github could be registered and configured to access GitHub. A default client can be registered for general access.- Codifies the concept of outgoing middleware via delegating handlers in
HttpClient
. Provides extensions for Polly-based middleware to take advantage of delegating handlers inHttpClient
.- Manages the pooling and lifetime of underlying
HttpClientMessageHandler
instances. Automatic management avoids common DNS (Domain Name System) problems that occur when manually managingHttpClient
lifetimes.- Adds a configurable logging experience (via
ILogger
) for all requests sent through clients created by the factory.
An example of usage is:
In startup.cs file:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient(); // <- add this
You can inject using this in a service or repository class:
public class BasicService : IBasicService
{
private readonly IHttpClientFactory _httpClientFactory;
public BasicUsageModel(IHttpClientFactory httpClientFactory) // <- inject here
{
_httpClientFactory = httpClientFactory;
}
or this if its razor page code behind:
[Inject] public IHttpClientFactory HttpClientFactory { get; set; }
or this if its razor page:
@inject IHttpClientFactory HttpClientFactory
And use it like this:
var httpClient = _clientFactory.CreateClient(); // <- create HTTP client