2

我想从 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");
        }
    }
}
4

2 回答 2

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

于 2019-08-04T02:28:22.150 回答
1

您可以在 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");
于 2020-09-13T14:20:17.750 回答