【发布时间】:2019-12-12 01:46:47
【问题描述】:
我想从 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?)
文档显示这是它是如何完成的。
复杂的服务可能需要额外的服务。在之前 例如,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");
}
}
}
【问题讨论】:
-
您缺少
using System.Net.Http;无法访问WeatherService.cs中的课程 -
要明确客户端或服务器端的 Blazor,对于 HttpClient 有一些细微的差别。
-
@HenkHolterman 你能详细说明你在问什么吗?出于这个原因,“客户端”在我的问题的标题中,特别是如果我理解你的意思的话。我错过了什么吗?
-
不,我只是错过了标题中的内容。正在查看文本和标签。
标签: c# blazor blazor-client-side