public class AuthenticationHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage req, CancellationToken cancellationToken)
{
Debug.WriteLine("Process request");
// Call the inner handler.
var response = await base.SendAsync(req, cancellationToken);
Debug.WriteLine("Process response");
return response;
}
}
解決方案檔案:https : //i.stack.imgur.com/M4yv6.png
我能找到的唯一答案是舊版本的 Web API,其中解決方案的結構非常不同
uj5u.com熱心網友回復:
如果您使用 DelegatingHandler 來實作從 Web API 到另一個服務的出站請求的橫切關注點,則可以使用 HttpClientFactory 注冊您的處理程式并將其附加到命名或型別化的 HttpClient:
從https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0#outgoing-request-middleware-1:
HttpClient 具有委托處理程式的概念,這些處理程式可以為傳出的 HTTP 請求鏈接在一起。IHttpClientFactory:
簡化定義要應用于每個命名客戶端的處理程式。
支持注冊和鏈接多個處理程式以構建傳出請求中間件管道。這些處理程式中的每一個都能夠在傳出請求之前和之后執行作業。這種模式:
類似于 ASP.NET Core 中的入站中間件管道。提供一種機制來管理圍繞 HTTP 請求的橫切關注點,例如:快取錯誤處理序列化日志
在這種方法下,您可以將啟動中的處理程式注冊到 DI 容器中,以便在將其注入或實體化到服務中的某個位置時,將其附加到使用客戶端進行的任何呼叫:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddTransient<AuthenticationHandler>();
services.AddHttpClient<MyTypedHttpClient>(c =>
{
c.BaseAddress = new Uri("https://localhost:5001/");
})
.AddHttpMessageHandler<AuthenticationHandler>();
// ...
}
如果您將行為附加到來自 API 使用者的 Web API 入站請求,則可以改用中間件:https : //docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/? view =aspnetcore -5.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/346534.html
標籤:C# asp.net asp.net核心 asp.net-web-api
