forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonHttpClientUtils.cs
More file actions
75 lines (61 loc) · 2.41 KB
/
JsonHttpClientUtils.cs
File metadata and controls
75 lines (61 loc) · 2.41 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
#nullable enable
#if !NET6_0_OR_GREATER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace ServiceStack;
public delegate object ResultsFilterHttpDelegate(Type responseType, string httpMethod, string requestUri, object request);
public delegate void ResultsFilterHttpResponseDelegate(HttpResponseMessage webResponse, object response, string httpMethod, string requestUri, object request);
public delegate object ExceptionFilterHttpDelegate(HttpResponseMessage webResponse, string requestUri, Type responseType);
public static class JsonApiClientUtils
{
public static Dictionary<string, string> ToDictionary(this HttpResponseHeaders headers)
{
var to = new Dictionary<string, string>();
foreach (var header in headers)
{
to[header.Key] = string.Join(", ", header.Value);
}
return to;
}
public static WebHeaderCollection ToWebHeaderCollection(this HttpResponseHeaders headers)
{
var to = new WebHeaderCollection();
foreach (var header in headers)
{
to[header.Key] = string.Join(", ", header.Value);
}
return to;
}
public static string? GetContentType(this HttpResponseMessage httpRes)
{
return httpRes.Headers.TryGetValues(HttpHeaders.ContentType, out var values)
? values.FirstOrDefault()
: null;
}
public static void AddBasicAuth(this HttpRequestMessage request, string userName, string password)
{
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
return;
request.Headers.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + password)));
}
public static void AddApiKeyAuth(this HttpRequestMessage request, string apiKey)
{
if (string.IsNullOrEmpty(apiKey))
return;
request.Headers.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes(apiKey + ":")));
}
public static void AddBearerToken(this HttpRequestMessage request, string bearerToken)
{
if (string.IsNullOrEmpty(bearerToken))
return;
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
}
}
#endif