88
99namespace WebMVC . Services . Utilities
1010{
11+ /// <summary>
12+ /// HttpClient wrapper that integrates Retry and Circuit
13+ /// breaker policies when calling to Api services.
14+ /// Currently is ONLY implemented for the ASP MVC
15+ /// and Xamarin App
16+ /// </summary>
1117 public class HttpApiClientWrapper : IHttpClient
1218 {
1319 private HttpClient _client ;
@@ -49,11 +55,11 @@ private Policy CreateRetryPolicy() =>
4955 Policy . Handle < HttpRequestException > ( )
5056 . WaitAndRetryAsync (
5157 // number of retries
52- 3 ,
58+ 3 ,
5359 // exponential backofff
5460 retryAttempt => TimeSpan . FromSeconds ( Math . Pow ( 2 , retryAttempt ) ) ,
5561 // on retry
56- ( exception , timeSpan , retryCount , context ) =>
62+ ( exception , timeSpan , retryCount , context ) =>
5763 {
5864 _logger . LogTrace ( $ "Retry { retryCount } " +
5965 $ "of { context . PolicyKey } " +
@@ -62,27 +68,21 @@ private Policy CreateRetryPolicy() =>
6268 }
6369 ) ;
6470
65- // Notice that these (and other methods below) are Task
66- // returning asynchronous methods. But, they do not
67- // have the 'async' modifier, and do not contain
68- // any 'await statements. In each of these methods,
69- // the only asynchronous call is the last (or only)
70- // statement of the method. In those instances,
71- // a Task returning method that does not use the
72- // async modifier is preferred. The compiler generates
73- // synchronous code for this method, but returns the
74- // task from the underlying asynchronous method. The
75- // generated code does not contain the state machine
76- // generated for asynchronous methods.
7771 public Task < string > GetStringAsync ( string uri ) =>
78- HttpInvoker ( ( ) => _client . GetStringAsync ( uri ) ) ;
72+ HttpInvoker ( ( ) =>
73+ _client . GetStringAsync ( uri ) ) ;
7974
8075 public Task < HttpResponseMessage > PostAsync < T > ( string uri , T item ) =>
8176 // a new StringContent must be created for each retry
8277 // as it is disposed after each call
83- HttpInvoker ( ( ) => _client . PostAsync ( uri ,
84- new StringContent ( JsonConvert . SerializeObject ( item ) ,
85- System . Text . Encoding . UTF8 , "application/json" ) ) ) ;
78+ HttpInvoker ( ( ) =>
79+ {
80+ var response = _client . PostAsync ( uri , new StringContent ( JsonConvert . SerializeObject ( item ) , System . Text . Encoding . UTF8 , "application/json" ) ) ;
81+ // raise exception if not success response
82+ // needed for circuit breaker to track fails
83+ response . Result . EnsureSuccessStatusCode ( ) ;
84+ return response ;
85+ } ) ;
8686
8787 public Task < HttpResponseMessage > DeleteAsync ( string uri ) =>
8888 HttpInvoker ( ( ) => _client . DeleteAsync ( uri ) ) ;
0 commit comments