This is my HttpService class, it works fine. But it seems weird, the code in every function much the same. And I should write try/catch in every functions, espcially TaskCanceledException, if I do not catch it here, my application will terminate. Could some one give me some example about how to optimize the code?
[Export(typeof(IDataSource))]
public class HttpService : IDataSource
{
HttpClient client = new HttpClient();
public HttpService()
{
client.BaseAddress = new Uri("https://localhost:3721");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public void Initialize(CurrentUser currentUser)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes(currentUser.Name + ":" + currentUser.Password)));
}
public async Task<IEnumerable<User>> getUsers()
{
try
{
var response = await client.GetAsync("api/User");
//response.EnsureSuccessStatusCode(); // Throw on error code.
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<IEnumerable<User>>();
return result;
}
else
{
return null;
}
}
catch (Newtonsoft.Json.JsonException ex)
{
Console.WriteLine(ex.ToString());
}
catch (HttpRequestException ex)
{
Console.WriteLine(ex.ToString());
}
catch (TaskCanceledException ex)
{
Console.WriteLine(ex.ToString());
}
return null;
}
public async Task<IEnumerable<permission>> getPermission()
{
try
{
var response = await client.GetAsync("api/User");
//response.EnsureSuccessStatusCode(); // Throw on error code.
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<IEnumerable<permission>>();
return result;
}
else
{
return null;
}
}
catch (Newtonsoft.Json.JsonException ex)
{
Console.WriteLine(ex.ToString());
}
catch (HttpRequestException ex)
{
Console.WriteLine(ex.ToString());
}
catch (TaskCanceledException ex)
{
Console.WriteLine(ex.ToString());
}
return null;
}
public async Task<CurrentUser> getCurrentUserInfo(User user)
{
try
{
var response = await client.GetAsync("api/User?name=" + user.Name);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<CurrentUser>();
return result;
}
else
{
return null;
}
}
catch (Newtonsoft.Json.JsonException ex)
{
Console.WriteLine(ex.ToString());
}
catch (HttpRequestException ex)
{
Console.WriteLine(ex.ToString());
}
catch (TaskCanceledException ex)
{
Console.WriteLine(ex.ToString());
}
return null;
}
}