-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseDocumentationRepository.cs
50 lines (45 loc) · 1.91 KB
/
BaseDocumentationRepository.cs
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
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace Documentation.Plugin.Core.Repository
{
public class BaseDocumentationRepository
{
protected HttpClient _client;
/// <summary>
/// builds http client with a basic auth header using the provided username and token.
/// </summary>
/// <param name="userName">api user</param>
/// <param name="token">api authorization token</param>
protected void BuildHttpClient(string userName, string token, string apiUrl)
{
_client = new HttpClient();
_client.BaseAddress = new Uri(apiUrl);
_client.DefaultRequestHeaders.Authorization = GetBasicAuthHeader(userName, token);
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Add("User-Agent", "Anything");
}
private AuthenticationHeaderValue GetBasicAuthHeader(string userName, string token)
{
string format = $"{userName}:{token}";
string authString = Convert.ToBase64String(Encoding.ASCII.GetBytes(format));
return new AuthenticationHeaderValue("Basic", authString);
}
/// <summary>
/// Returns the response of the request url as a string on status code 200 reponse. Otherwise returns empty string
/// </summary>
/// <param name="requestUrl">url of request</param>
/// <returns>string response</returns>
protected string GetDocumentationData(string requestUrl)
{
using (var httpResponse = _client.GetAsync(requestUrl).Result)
{
if (httpResponse.StatusCode != HttpStatusCode.OK)
return string.Empty;
return httpResponse.Content.ReadAsStringAsync().Result;
}
}
}
}