当我尝试注入 HttpClient 时,剃刀页面出现错误:
未处理的承诺拒绝:错误:System.InvalidOperationException:无法为 type 上的属性“Http”提供值。没有“System.Net.Http.HttpClient”类型的注册服务。
请审查并提供反馈。
当我尝试注入 HttpClient 时,剃刀页面出现错误:
未处理的承诺拒绝:错误:System.InvalidOperationException:无法为 type 上的属性“Http”提供值。没有“System.Net.Http.HttpClient”类型的注册服务。
请审查并提供反馈。
如果您提供代码片段您正在尝试做的事情,那么回答您的问题会更容易。但是没问题。现在我将向您展示一个示例,使用 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();
}
在Razor Component
它不需要@inject
请参见下面的示例:
<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>
而这@code
部分
@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();
}
}
}
这对我有用.. =)
该消息说您需要在文件 Program.cs 中注册服务 HTTP
如果你使用 Net6,你可以用这一行注册:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient();