C # HttpClient GetAsync interception

I have a web project (C #, MVC5 but not WebAPI) and a simple HTTP REST client that calls an external REST service and receives an accessToken link.

I want to check the response from all the Get / PostAsync calls for statusCode 401, but I see that when implementing the DelegatingHandler I can override the SendAsync method.

 class CustomDelegatingHandler : DelegatingHandler { async protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { HttpResponseMessage response = await base.SendAsync(request, cancellationToken); if (response.StatusCode == HttpStatusCode.Unauthorized) { 

Is there anything else I can do to not change the implementation of all my asynchronous calls to use SendAsync ?

(What I really want to do is update the accessToken.)

+4
Mar 17 '15 at 18:10
source share
2 answers

I think you're on the right track. You will not need to change your calls to use SendAsync instead of GetAsync , PostAsync , etc. Rather, you will need to change the way you create an instance of HttpClient :

 var client = new HttpClient(new CustomDelegatingHandlerTokenRefresher()); // GetAsync, PostAsync, etc will hit your handler 
+5
Mar 17 '15 at 21:32
source

Use the Decorator or Interceptor template.

An example of a specific 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); } } 
+1
Mar 17 '15 at 18:17
source



All Articles