Skip to content

Commit

Permalink
HttpClientFactory now supports initialization using baseUrl
Browse files Browse the repository at this point in the history
  • Loading branch information
VahidFarahmandian committed Jul 1, 2023
1 parent 93035a3 commit a1285c9
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ namespace Jinget.Handlers.ExternalServiceHandlers.DefaultServiceHandler
{
public class JingetServiceHandler<TResponseModel> : ServiceHandler<JingetServiceHandlerEvents<TResponseModel>> where TResponseModel : class, new()
{
public JingetServiceHandler(string baseUri, bool ignoreSslErrors = false, Dictionary<string, string> headers = null) : base(baseUri, ignoreSslErrors, headers) { }

private async Task<TResponseModel> ProcessTask(Func<Task<HttpResponseMessage>> task)
{
TResponseModel responseModel = null;
Expand Down Expand Up @@ -45,10 +47,12 @@ private async Task<TResponseModel> ProcessTask(Func<Task<HttpResponseMessage>> t
return responseModel;

}
public async Task<TResponseModel> GetAsync(string baseUri, string requestUri, bool ignoreSslErrors = false, Dictionary<string, string> headers = null) => await ProcessTask(async () => await HttpClientFactory.GetAsync(baseUri, requestUri, ignoreSslErrors, headers));
public async Task<TResponseModel> GetAsync(string url, Dictionary<string, string> headers = null)
=> await ProcessTask(async () => await HttpClientFactory.GetAsync(url, headers));

public async Task<TResponseModel> PostAsync(string baseUri, object content = null, bool ignoreSslErrors = false, Dictionary<string, string> headers = null) => await ProcessTask(async () => await HttpClientFactory.PostAsync(baseUri, content, ignoreSslErrors, headers));
public async Task<TResponseModel> PostAsync(string url, object content = null, Dictionary<string, string> headers = null)
=> await ProcessTask(async () => await HttpClientFactory.PostAsync(url, content, headers));

public async Task<TResponseModel> SendAsync(string baseUri, HttpRequestMessage message, bool ignoreSslErrors = false) => await ProcessTask(async () => await HttpClientFactory.SendAsync(baseUri, message, ignoreSslErrors));
public async Task<TResponseModel> SendAsync(HttpRequestMessage message) => await ProcessTask(async () => await HttpClientFactory.SendAsync(message));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@

namespace Jinget.Handlers.ExternalServiceHandlers.ServiceHandler.Factory
{
public class HttpClientFactory : ObjectFactory<HttpClient>
public class HttpClientFactory
{
protected override HttpClient GetInstance(string baseUri, bool ignoreSslErrors = false, Dictionary<string, string> headers = null)
readonly HttpClient client;
internal HttpClientFactory(string baseUri, bool ignoreSslErrors = false, Dictionary<string, string> headers = null)
{
HttpClient client;
if (ignoreSslErrors)
{
var httpClientHandler = new HttpClientHandler
Expand All @@ -35,26 +35,40 @@ protected override HttpClient GetInstance(string baseUri, bool ignoreSslErrors =
BaseAddress = new Uri(baseUri)
};
}
}

client.DefaultRequestHeaders.Clear();

private Uri GetUrl(string url)
{
string baseUrl = client.BaseAddress.ToString().EndsWith("/") ? client.BaseAddress.ToString() : $"{client.BaseAddress}/";
return new Uri($"{baseUrl}{url}".TrimEnd('/'));
}
private void SetHeaders(Dictionary<string, string>? headers)
{
if (headers == null)
return;
foreach (var header in headers)
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json));
}
else
{
foreach (var header in headers)
if (header.Key == "Authorization")
{
if (header.Value.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", header.Value[7..]);
else if (header.Value.StartsWith("Basic ", StringComparison.InvariantCultureIgnoreCase))
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", header.Value[6..]);
else if (header.Value.StartsWith("Digest ", StringComparison.InvariantCultureIgnoreCase))
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Digest", header.Value[7..]);
}
else
{
client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
}
}

return client;
}

public override async Task<HttpResponseMessage> PostAsync(string baseUri, object content = null, bool ignoreSslErrors = false, Dictionary<string, string> headers = null)
public async Task<HttpResponseMessage> PostAsync(string url, object content = null, Dictionary<string, string> headers = null)
{
if (url != "" && url.StartsWith("/"))
throw new Jinget.Core.Exceptions.JingetException($"{nameof(url)} should not start with '/'");

StringContent bodyContent = null;
if (content != null)
{
Expand All @@ -75,11 +89,19 @@ public override async Task<HttpResponseMessage> PostAsync(string baseUri, object
}
headers?.Remove("Content-Type");
}
return await GetInstance(baseUri, ignoreSslErrors, headers).PostAsync(baseUri, bodyContent);

SetHeaders(headers);
return await client.PostAsync(GetUrl(url), bodyContent);
}

public override async Task<HttpResponseMessage> GetAsync(string baseUri, string requestUri, bool ignoreSslErrors = false, Dictionary<string, string> headers = null) => await GetInstance(baseUri, ignoreSslErrors, headers).GetAsync(baseUri + requestUri);
public async Task<HttpResponseMessage> GetAsync(string url, Dictionary<string, string> headers = null)
{
if (url.StartsWith("/"))
throw new Jinget.Core.Exceptions.JingetException($"{nameof(url)} should not start with '/'");
SetHeaders(headers);
return await client.GetAsync(GetUrl(url));
}

public override async Task<HttpResponseMessage> SendAsync(string baseUri, HttpRequestMessage message, bool ignoreSslErrors = false) => await GetInstance(baseUri, ignoreSslErrors).SendAsync(message);
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage message) => await client.SendAsync(message);
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Jinget.Handlers.ExternalServiceHandlers.ServiceHandler.Factory;
using System.Collections.Generic;

namespace Jinget.Handlers.ExternalServiceHandlers.ServiceHandler
{
Expand All @@ -8,10 +9,10 @@ namespace Jinget.Handlers.ExternalServiceHandlers.ServiceHandler

protected HttpClientFactory HttpClientFactory { get; set; }

protected ServiceHandler()
protected ServiceHandler(string baseUri, bool ignoreSslErrors = false, Dictionary<string, string> headers = null)
{
Events = new T();
HttpClientFactory = new HttpClientFactory();
HttpClientFactory = new HttpClientFactory(baseUri, ignoreSslErrors, headers);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class JingetServiceHandlerTests
[TestMethod()]
public async Task should_call_get_restapi()
{
var jingetServiceHandler = new JingetServiceHandler<List<SampleGetResponse>>();
var jingetServiceHandler = new JingetServiceHandler<List<SampleGetResponse>>("https://jsonplaceholder.typicode.com");
jingetServiceHandler.Events.ServiceCalled += (object sender, HttpResponseMessage e) =>
{
Assert.IsTrue(e.IsSuccessStatusCode);
Expand All @@ -27,15 +27,16 @@ public async Task should_call_get_restapi()
{
Assert.IsFalse(e is null);
};
var result = await jingetServiceHandler.GetAsync("https://jsonplaceholder.typicode.com", "/users", true, null);

var result = await jingetServiceHandler.GetAsync("users");

Assert.IsFalse(result is null);
}

[TestMethod()]
public async Task should_call_post_restapi()
{
var jingetServiceHandler = new JingetServiceHandler<SamplePostResponse>();
var jingetServiceHandler = new JingetServiceHandler<SamplePostResponse>("https://jsonplaceholder.typicode.com", true, null);
jingetServiceHandler.Events.ServiceCalled += (object sender, HttpResponseMessage e) =>
{
Assert.IsTrue(e.IsSuccessStatusCode);
Expand All @@ -53,15 +54,13 @@ public async Task should_call_post_restapi()
Assert.IsFalse(e is null);
};
var result = await jingetServiceHandler
.PostAsync(
"https://jsonplaceholder.typicode.com/posts",
.PostAsync("posts",
new
{
title = "foo",
body = "bar",
userId = 1,
},
true,
new Dictionary<string, string>
{
{"Content-type","application/json; charset=UTF-8" }
Expand All @@ -73,7 +72,7 @@ public async Task should_call_post_restapi()
[TestMethod()]
public async Task should_call_send_restapi()
{
var jingetServiceHandler = new JingetServiceHandler<SamplePutResponse>();
var jingetServiceHandler = new JingetServiceHandler<SamplePutResponse>("https://jsonplaceholder.typicode.com", true, null);
jingetServiceHandler.Events.ServiceCalled += (object sender, HttpResponseMessage e) =>
{
Assert.IsTrue(e.IsSuccessStatusCode);
Expand All @@ -93,6 +92,7 @@ public async Task should_call_send_restapi()

var request = new HttpRequestMessage
{
RequestUri = new Uri("https://jsonplaceholder.typicode.com/posts/1"),
Method = HttpMethod.Put,
Content = new StringContent(JsonConvert.SerializeObject(new
{
Expand All @@ -104,15 +104,15 @@ public async Task should_call_send_restapi()
};
request.Headers.TryAddWithoutValidation("Content-type", "application/json; charset=UTF-8");

var result = await jingetServiceHandler.SendAsync("https://jsonplaceholder.typicode.com/posts/1", request);
var result = await jingetServiceHandler.SendAsync(request);

Assert.IsFalse(result is null);
}

[TestMethod()]
public async Task should_call_get_soap()
{
var jingetServiceHandler = new JingetServiceHandler<AddResponse>();
var jingetServiceHandler = new JingetServiceHandler<AddResponse>("http://www.dneonline.com/calculator.asmx");
jingetServiceHandler.Events.ServiceCalled += (object sender, HttpResponseMessage e) =>
{
Assert.IsTrue(e.IsSuccessStatusCode);
Expand All @@ -133,13 +133,14 @@ public async Task should_call_get_soap()
var (envelope, request) = new SampleSOAPRequest().CreateEnvelope();
envelope.Body.Add = new SampleSOAPRequest.SampleSOAPGet { intA = 1, intB = 2 };

var result = await jingetServiceHandler.PostAsync("http://www.dneonline.com/calculator.asmx", envelope.ToString(), true, new Dictionary<string, string>
var result = await jingetServiceHandler.PostAsync("", envelope.ToString(), new Dictionary<string, string>
{
{"Content-Type","text/xml" },
{"SOAPAction","http://tempuri.org/Add" }
});

Assert.IsFalse(result is null);
Assert.AreEqual(3, result.AddResult);
}
}
}

0 comments on commit a1285c9

Please sign in to comment.