-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathHttpBuilder.cs
More file actions
82 lines (73 loc) · 3.05 KB
/
HttpBuilder.cs
File metadata and controls
82 lines (73 loc) · 3.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace StackExchange.Utils
{
internal class HttpBuilder : IRequestBuilder
{
public HttpSettings Settings { get; }
public HttpRequestMessage Message { get; }
public bool LogErrors { get; set; } = true;
public IEnumerable<HttpStatusCode> IgnoredResponseStatuses { get; set; } = Enumerable.Empty<HttpStatusCode>();
public IEnumerable<HttpStatusCode> LogErrorResponseBodyStatuses { get; set; } = Enumerable.Empty<HttpStatusCode>();
public TimeSpan Timeout { get; set; }
public IWebProxy Proxy { get; set; }
public bool BufferResponse { get; set; } = true;
public IHttpClientPool ClientPool { get; set; }
public event EventHandler<HttpExceptionArgs> BeforeExceptionLog;
private readonly string _callerName, _callerFile;
private readonly int _callerLine;
public HttpBuilder(string uri, HttpSettings settings, string callerName, string callerFile, int callerLine)
{
Message = new HttpRequestMessage
{
RequestUri = new Uri(uri, UriKind.RelativeOrAbsolute)
};
Settings = settings;
Timeout = (settings ?? Http.DefaultSettings).DefaultTimeout;
Proxy = (settings ?? Http.DefaultSettings).DefaultProxyFactory?.Invoke();
_callerName = callerName;
_callerFile = callerFile;
_callerLine = callerLine;
}
public void OnBeforeExceptionLog(HttpExceptionArgs args)
{
BeforeExceptionLog?.Invoke(this, args);
}
internal void AddExceptionData(Exception ex)
{
if (ex == null)
{
return;
}
try
{
var servicePoint = ServicePointManager.FindServicePoint(Message.RequestUri);
if (servicePoint != null)
{
ex.AddLoggedData("ServicePoint.ConnectionLimit", servicePoint.ConnectionLimit)
.AddLoggedData("ServicePoint.CurrentConnections", servicePoint.CurrentConnections)
.AddLoggedData("ServicePointManager.CurrentConnections", ServicePointManager.DefaultConnectionLimit);
}
}
catch { }
ex.AddLoggedData("Caller.Name", _callerName)
.AddLoggedData("Caller.File", _callerFile)
.AddLoggedData("Caller.Line", _callerLine.ToString());
}
public IRequestBuilder<T> WithHandler<T>(Func<HttpResponseMessage, Task<T>> handler) => new HttpBuilder<T>(this, handler);
}
internal class HttpBuilder<T> : IRequestBuilder<T>
{
public IRequestBuilder Inner { get; }
public Func<HttpResponseMessage, Task<T>> Handler { get; }
public HttpBuilder(HttpBuilder builder, Func<HttpResponseMessage, Task<T>> handler)
{
Inner = builder;
Handler = handler;
}
}
}