Reputation: 159
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.
Upvotes: 9
Views: 7184
Reputation: 141
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();
Upvotes: 4
Reputation: 21
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();
}
Upvotes: 2
Reputation: 928
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.. =)
Upvotes: 0