I am trying to using HttpClient for making API calls from a different domain and for that purpose I have created the following service class after doing some research. It is 4.7.2 framework and not a .NET core system. I have created library class for this with following classes. Please give me your valuable suggestions for changes or enhancements
IRequestService.cs file
public interface IRequestService
{
Task<TResult> GetAsync<TResult>(HttpClientNS client, string url);
Task<string> GetStringAsync(HttpClientNS client, string url);
Task<TResult> PostAsync<TRequest, TResult>(HttpClientNS client, TRequest t, string url);
HttpClientNS GetClient();
}
RequestService.cs
public class RequestService : IRequestService
{
private readonly string _hostWebApiUrl;
private readonly string _apiAuthKey;
public RequestService()
{
_hostWebApiUrl = Config.AppSettings["TestWebApiURL"];
_apiAuthKey = Config.AppSettings["ApiKey"];
}
public RequestService(string hostWebApiUrl, string apiAuthKey)
{
_hostWebApiUrl = hostWebApiUrl;
_apiAuthKey = apiAuthKey;
}
public HttpClientNS GetClient()
{
string _baseAddress = _hostWebApiUrl;
var client = new HttpClientNS
{
BaseAddress = new Uri(_baseAddress)
};
client.DefaultRequestHeaders.Add("AuthApiKey", _apiAuthKey);
return client;
}
public async Task<TResult> GetAsync<TResult>(HttpClientNS client, string url)
{
client.Timeout = TimeSpan.FromSeconds(30);
var result = default(TResult);
try
{
var response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
//var jsonString = await response.Content.ReadAsStringAsync();
//var result = JsonConvert.DeserializeObject<TResult>(jsonString);
await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
{
if (x.IsFaulted)
throw x.Exception;
result = JsonConvert.DeserializeObject<TResult>(x.Result);
});
}
catch (Exception ex)
{
}
return result;
}
public async Task<string> GetStringAsync(HttpClientNS client, string url)
{
var httpRequest = new HttpRequestMessage(new HttpMethod("GET"), url);
var response = client.SendAsync(httpRequest).Result;
var jsonString = await response.Content.ReadAsStringAsync();
return jsonString;
}
public async Task<TResult> PostAsync<TRequest, TResult>(HttpClientNS client, TRequest t, string url)
{
var result = default(TResult);
var json = JsonConvert.SerializeObject(t);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
//response.EnsureSuccessStatusCode();
//var jsonString = await response.Content.ReadAsStringAsync();
//var result = JsonConvert.DeserializeObject<TResult>(jsonString);
//return result;
var response = await client.PostAsync(url, httpContent).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
{
if (x.IsFaulted)
throw x.Exception;
result = JsonConvert.DeserializeObject<TResult>(x.Result);
});
return result;
}
}
I am making calls to these wrapper class containing generic methods as follows:
public class TestApiClient
{
private IRequestService RequestService;
private readonly string _apiUrl;
public TestApiClient(IRequestService request)
{
RequestService = new RequestService();
_apiUrl = "api/TestCustomer";
}
public async Task<bool> IsCustomerVendor(int vendorId)
{
var url = string.Format(_apiUrl + "/IsCUstomerVendor?vendorId={0}", vendorId);
var client = RequestService.GetClient();
var result = await RequestService.GetAsync<bool>(client, url);
return result;
}
public async Task<bool> IsCUstomerDataInvalid(int productId, int financeCompanyId, string balloonDealerState)
{
var url = _apiUrl + "/IsCUstomerDataInvalid";
var content = new { CustomerId = customerId, CompanyId = companyId, DealerState = DealerState };
//var result = _webClientHelper.PostContent<bool>(url, content);
var client = RequestService.GetClient();
var result = await RequestService.PostAsync<Object,bool>(client, content, url);
return result;
}
}
HttpClientNS
? \$\endgroup\$client.SendAsync(httpRequest).Result;
always preferawait
. \$\endgroup\$