try to use this functions:
public async Task<M> ConnectHttpClient<R, M>(string apiUrl, R reqModel)
{
M model = default(M);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl, reqModel);
if (response.IsSuccessStatusCode)
{
var res = response.Content.ReadAsStringAsync().Result;
model = JsonConvert.DeserializeObject<M>(res);
}
return model;
}
public async Task<M> ConnectRestClient<R, M>(string apiUrl, R reqModel)
{
M model = default(M);
RestClient restClient = new RestClient(apiUrl);
RestRequest restRequest = new RestRequest(apiUrl, RestSharp.Method.Post);
restRequest.AddParameter(
"application/json",
JsonConvert.SerializeObject(reqModel),
ParameterType.RequestBody);
RestResponse restResponse = await restClient.ExecuteAsync(restRequest);
if (restResponse.IsSuccessful)
{
string response = restResponse.Content;
model = JsonConvert.DeserializeObject<M>(response);
}
return model;
}
example usage :
var result1 = await service.ConnectHttpClient<User, List<User>>("api/User/GetUserInfoByUserId", new User() { UserId = 1 });
var result2 = await service.ConnectRestClient<User, List<User>>("api/User/GetUserInfoByUserId", new User() { UserId = 1 });