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

时间:2019-08-04 02:07:48

标签: c# blazor blazor-client-side

我想从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   创建服务,它会识别出所需的服务   构造函数并相应地提供它们。

来源: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");
        }
    }
}

2 个答案:

答案 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");