Intercept C# HttpClient GetAsync

耗尽温柔 提交于 2019-12-04 10:20:14

I think you're on the right track. You wouldn't need to change your calls to use SendAsync instead of GetAsync, PostAsync, etc though. Rather, you'd need to change how you instantiate HttpClient:

var client = new HttpClient(new CustomDelegatingHandlerTokenRefresher());
// GetAsync, PostAsync, etc will hit your handler
Silas Reinagel

Use the Decorator or Interceptor pattern.

Example concrete decorator:

public class CustomDelegatingHandlerTokenRefresher() : DelegatingHandler
{
    public CustomDelegatingHandlerTokenRefresher(DelegatingHandler handler)
    {
        InnerHandler = handler;
    }

    protected override async Task<HttpResponseMessage> SendAsync(
      HttpRequestMessage request, CancellationToken cancellationToken)
    {
        RefreshToken();
        return await InnerHandler.SendAsync(request, cancellationToken);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!