1
+ using System ;
2
+ using System . Net ;
3
+ using System . Net . Http ;
4
+ using System . Threading ;
5
+ using System . Threading . Tasks ;
6
+
7
+ namespace FireSharp
8
+ {
9
+ internal class AutoRedirectHttpClientHandler : DelegatingHandler
10
+ {
11
+ private int _maximumAutomaticRedirections ;
12
+
13
+ public int MaximumAutomaticRedirections
14
+ {
15
+ get { return _maximumAutomaticRedirections ; }
16
+ set
17
+ {
18
+ if ( value < 1 )
19
+ {
20
+ throw new ArgumentException ( "The specified value must be greater than 0." ) ;
21
+ }
22
+
23
+ _maximumAutomaticRedirections = value ;
24
+ }
25
+ }
26
+
27
+ public AutoRedirectHttpClientHandler ( )
28
+ {
29
+ var handler = new HttpClientHandler { AllowAutoRedirect = false } ;
30
+ InnerHandler = handler ;
31
+ MaximumAutomaticRedirections = handler . MaxAutomaticRedirections ;
32
+ }
33
+
34
+ protected override async Task < HttpResponseMessage > SendAsync ( HttpRequestMessage request , CancellationToken cancellationToken )
35
+ {
36
+ var response = await base . SendAsync ( request , cancellationToken ) . ConfigureAwait ( false ) ;
37
+
38
+ if ( ! IsRedirect ( response ) )
39
+ {
40
+ return response ;
41
+ }
42
+
43
+ var redirectCount = 0 ;
44
+
45
+ while ( IsRedirect ( response ) )
46
+ {
47
+ redirectCount ++ ;
48
+
49
+ if ( redirectCount > MaximumAutomaticRedirections )
50
+ {
51
+ throw new WebException ( "Too many automatic redirections were attempted." ) ;
52
+ }
53
+
54
+ request . RequestUri = response . Headers . Location ;
55
+ response = await SendAsync ( request , cancellationToken ) . ConfigureAwait ( false ) ;
56
+ }
57
+
58
+ return response ;
59
+ }
60
+
61
+ private static bool IsRedirect ( HttpResponseMessage response )
62
+ {
63
+ switch ( response . StatusCode )
64
+ {
65
+ case HttpStatusCode . MovedPermanently :
66
+ case HttpStatusCode . Redirect :
67
+ case HttpStatusCode . RedirectMethod :
68
+ case HttpStatusCode . RedirectKeepVerb :
69
+ return true ;
70
+ default :
71
+ return false ;
72
+ }
73
+ }
74
+ }
75
+ }
0 commit comments