[英]Unable to resolve service for type 'System.Lazy`1[System.Net.Http.IHttpClientFactory]' while attempting to activate service
[英]There is no registered service of type 'System.Net.Http.IHttpClientFactory
我試圖在 Blazor 服務器中執行 http 發布請求。 我嘗試發送用戶名和密碼
這是我撥打 web Api 電話的部分:
private IEnumerable<yolo> test = Array.Empty<yolo>();
private bool getBranchesError;
private bool shouldRender;
protected override async Task OnInitializedAsync()
{
var request = new HttpRequestMessage(HttpMethod.Post,
"https://url.com");
request.Headers.Add("Accept", "application/vnd.github.json");
request.Headers.Add("User-Agent", "HttpClientFactory-Sample");
var client = ClientFactory.CreateClient();
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
using var responseStream = await response.Content.ReadAsStreamAsync();
test = await JsonSerializer.DeserializeAsync
<IEnumerable<yolo>>(responseStream);
}
else
{
getBranchesError = true;
}
shouldRender = true;
}
public class yolo
{
[JsonPropertyName("name")]
public string Name { get; set; }
}
這是我的 Program.cs
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may
want to change this for production scenarios,
see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
//http Client
builder.Services.AddHttpClient();
我知道這很混亂,但我已經嘗試了 6 個小時來解決它:D
這是錯誤消息
我的目標是它不再崩潰
如果您需要更多信息,請寫評論:D
當你在你的Startup
class 做var app = builder.build();
你含蓄地說“我已經完成了注冊服務”。 所以你需要移動你的builder.Services.AddHttpClient();
到那條線之前的某個地方使它工作,它不能在最后。
我會發布一個更完整的示例來說明我的意思,但是代碼在屏幕截圖中,這使得重新鍵入所有內容變得非常困難。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.