如何在服务中为 Blazor 客户端应用程序调用 HttpClient

How Do I Call HttpClient in Service for a Blazor Client-Side App

我想从 Blazor 中的服务进行 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?)

文档显示它是如何完成的。

Complex services might require additional services. In the prior example, DataAccess might require the HttpClient default service. @inject (or the InjectAttribute) isn't available for use in services. Constructor injection must be used instead. Required services are added by adding parameters to the service's constructor. When DI creates the service, it recognizes the services it requires in the constructor and provides them accordingly.

来源:https://docs.microsoft.com/en-us/aspnet/core/blazor/dependency-injection?view=aspnetcore-3.0#use-di-in-services

如何纠正错误?

// 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

中的 class
// 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
        }

    }
}

如果使用 class System.Net.Http.HttpClient 的全名不起作用,那么您肯定缺少对程序集的引用。

您可以在startup.cs中配置httpclient。

    services.AddHttpClient();
    services.AddScoped<HttpClient>();

现在您可以在 .razor 文件中使用 HttpClient。

@inject HttpClient httpClient

-------------

private async Task LoadSystems() => systemsList = await httpClient.GetJsonAsync<List<Models.Systems>>("Systems/GetSystems");