在 Asp.Net Core 中注冊自定義服務時,例如:
services.AddScoped<ISomeService, SomeService>();
然后,您可以開箱即用地從 SomeService 類的承包商訪問 Microsoft ILogger。
但是如果你注冊一個自定義的 HttpClient,比如:
services.AddHttpClient<ISomeHttpClient, SomeHttpClient>(client =>
{
client.BaseAddress = new Uri(Configuration["Url"]);
client.DefaultRequestHeaders.Add("Accept", "application/json");
});
然后,您無法從 SomeHttpClient 的建構式訪問 Microsoft ILogger。我收到錯誤:
無法決議“Microsoft.Extensions.Logging.ILogger”型別的服務
我知道該框架已經在為您記錄 HttpRequest 活動。我想做的是記錄每個請求的正文,以防 StatusCode 不成功。
任何想法如何實作這一目標?
uj5u.com熱心網友回復:
你能用ILogger<SomeHttpClient> logger比ILogger直接用嗎?
這是一些可以執行此操作并正常作業的代碼。
public class GitHubService
{
private readonly HttpClient _client;
private readonly ILogger<GitHubService> _logger;
public GitHubService(HttpClient client, ILogger<GitHubService> logger)
{
client.BaseAddress = new Uri("https://api.github.com/");
// GitHub API versioning
client.DefaultRequestHeaders.Add("Accept",
"application/vnd.github.v3 json");
// GitHub requires a user-agent
client.DefaultRequestHeaders.Add("User-Agent",
"HttpClientFactory-Sample");
_client = client;
_logger = logger;
}
public async Task<IEnumerable<string>> GetAspNetDocsIssues()
{
_logger.LogInformation("Getting issues from GitHub");
return await _client.GetFromJsonAsync<IEnumerable<string>>(
"/repos/aspnet/AspNetCore.Docs/issues?state=open&sort=created&direction=desc");
}
}
源代碼:https : //docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347647.html
標籤:asp.net核心 .net核心 asp.net-web-api asp.net-core-webapi .net-5
上一篇:獲取毫秒圖令牌失敗
