我如何为HTTPCLIENT打电话给Glazor Client端应用程序



我想从大火中的服务中进行HTTP调用,而不是在.razor文件中的@code块中拨打电话,也不是在代码范围内进行呼叫。我收到错误:
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(或注射tribute(可用于服务。 必须使用构造函数注入。所需的服务是 通过将参数添加到服务的构造函数中。当di时 创建服务,它识别其在 构造函数并相应地提供它们。

来源:https://learn.microsoft.com/en-us/aspnet/core/blazor/blazor/depplendency-indoction?view = asspnetcore-3.0#use-di-in-services <</em>

我该如何解决错误?

// 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");
        }
    }
}

您缺少 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的全名不起作用,那么您肯定会缺少对程序集的引用。

您可以在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");