我想从Blazor中的服务进行Http调用,而不是在@code
文件或代码隐藏中的.razor
块中进行调用。我收到错误消息:
Shared/WeatherService.cs(16,17): error CS0246: The type or namespace name 'HttpClient' could not be found (are you missing a using directive or an assembly reference?)
文档显示是的完成方式。
复杂的服务可能需要其他服务。在之前 例如,DataAccess可能需要HttpClient默认服务。 @inject(或InjectAttribute)不适用于服务。 必须使用构造函数注入。所需的服务是 通过向服务的构造函数添加参数来添加。当DI 创建服务,它会识别出所需的服务 构造函数并相应地提供它们。
我该如何纠正错误?
// WeatherService.cs
using System.Threading.Tasks;
namespace MyBlazorApp.Shared
{
public interface IWeatherService
{
Task<Weather> Get(decimal latitude, decimal longitude);
}
public class WeatherService : IWeatherService
{
public WeatherService(HttpClient httpClient)
{
...
}
public async Task<Weather> Get(decimal latitude, decimal longitude)
{
// Do stuff
}
}
}
// Starup.cs
using Microsoft.AspNetCore.Components.Builder;
using Microsoft.Extensions.DependencyInjection;
using MyBlazorApp.Shared;
namespace MyBlazorApp
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IWeatherService, WeatherService>();
}
public void Configure(IComponentsApplicationBuilder app)
{
app.AddComponent<App>("app");
}
}
}
答案 0 :(得分:4)
您缺少using System.Net.Http;
才能访问WeatherService.cs
中的课程
// WeatherService.cs
using System.Threading.Tasks;
using System.Net.Http; //<-- THIS WAS MISSING
namespace MyBlazorApp.Shared {
public interface IWeatherService {
Task<Weather> Get(decimal latitude, decimal longitude);
}
public class WeatherService : IWeatherService {
private HttpClient httpClient;
public WeatherService(HttpClient httpClient) {
this.httpClient = httpClient;
}
public async Task<Weather> Get(decimal latitude, decimal longitude) {
// Do stuff
}
}
}
如果对类System.Net.Http.HttpClient
使用全名不起作用,那么您肯定缺少对该程序集的引用。
答案 1 :(得分:0)
您可以在startup.cs中配置httpclient。
services.AddHttpClient();
services.AddScoped<HttpClient>();
现在您可以在.razor文件中使用HttClient。
@inject HttpClient httpClient
-------------
private async Task LoadSystems() => systemsList = await httpClient.GetJsonAsync<List<Models.Systems>>("Systems/GetSystems");