Server-side Blazor does not provide HttpClient for injection
Asked Answered
P

3

9

I get an error in razor page when I try to inject HttpClient:

Unhandled Promise Rejection: Error: System.InvalidOperationException: Cannot provide a value for property 'Http' on type . There is no registered service of type 'System.Net.Http.HttpClient'.

Kindly review and give feedback.

Paulita answered 18/3, 2019 at 11:24 Comment(0)
C
3

That message says that you need to register the service HTTP in file Program.cs

If you use Net6, you can register with this line:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient();
Corydon answered 1/3, 2022 at 16:52 Comment(0)
C
2

it would be easier to answer your question if you give code-snippets what you are trying to do. But ok. For now I will show you an example what you have to do, to inject a Service with DI.

ChartDataService.cs


namespace MyBlazorApp.Services 
{

  public class ChartDataService: IChartDataService
  {
    public HttpClient httpClient;
    
    public ChartDataService(HttpClient httpClient) 
    {
      this.httpClient = httpClient;
    }

    public async Task < IEnumerable < ChartData >> GetChartData()
    {
      return await httpClient.GetJsonAsync < ChartData[] > ($ "myUri");
    }
  }
}

IChartDataService.cs

namespace MyBlazorApp.Services 
{
  public interface IChartDataService 
  {
    Task < IEnumerable < ChartData >> GetChartData();
  }
}

Startup.cs
// other

public void ConfigureServices(IServiceCollection services) 
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    // some services
    services.AddHttpClient < IChartDataService, ChartDataService > (client => 
    {
      client.BaseAddress = new Uri(myBaseUri);
    });    
}

MyRazorPage.razor.cs (when using code Behind)

[Inject] private IChartDataService ChartDataService { get; set; }

or in
MyRazorPage.razor

@code
{
[Inject] private IChartDataService ChartDataService { get; set; }
}

then in your code - block or code - behind file u can use something like this,
  for example, in an async function..

protected override async Task OnInitializedAsync() 
{
  chartData = await ChartDataService.MakeChartData();
}
Cerement answered 17/7, 2020 at 9:36 Comment(0)
P
0

In Razor Component it's not needed to @inject

See the example below:

<div class="row">
    <div class="col-4">
        <label for="cities">Choose city</label>
        <input type="text" class="form-control" id="citiy" @bind="@cityName" />         
    </div>
    <div class="col-3">
        <button class="btn btn-primary" @onclick=@GetWeather>Get weather for @cityName</button>
    </div>
</div>
<div class="row">
    <div class="col-8 offset-2">
        <pre id="json"><code>@ResultStr</code></pre>
   </div>
</div>

And the @code part

@code {

    string cityName = "";
    string ResultStr= "...";
    string reqUrl => $"http://api.openweathermap.org/data/2.5/weather?q={cityName}&APPID=appID";

    async Task GetWeather()
    {
        try
        {
            HttpClient client = new HttpClient();
            ResultStr= "...";
            var response = await client.GetAsync(reqUrl);
            if (response.IsSuccessStatusCode)
                ResultStr= await response.Content.ReadAsStringAsync();
            else
                ResultStr= response.ReasonPhrase;
        }
        catch (Exception ex)
        {
             ResultStr= ex.ToString();
        }
    }
}

That worked for me.. =)

Pulsatile answered 18/11, 2019 at 14:27 Comment(1)
In Blazor, It's a best practice to inject HttpClient' not new HttpClient ()Batangas

© 2022 - 2024 — McMap. All rights reserved.