C# 和 .NET 中的 HttpInterceptor 实现

Vis*_*arp 4 .net c#

在 Angular 中,有 HttpInterceptor,它可以很好地拦截应用程序上的 HttpClient 调用,还可以处理请求的错误。

是否有一个 C#/.NET 库可以做同样的事情?

jjc*_*hiw 5

HttpClientHandler

你必须覆盖SendAsync

internal class MyHttpClientHandler : HttpClientHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
         // Do before call

        var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

        // do after call

        return response;
    }
}

var handler = new MyHttpClientHandler();

var client = new HttpClient(handler)
{
    BaseAddress = new Uri("my-api-uri")
};

Run Code Online (Sandbox Code Playgroud)