これは私の HttpService クラスです。正常に動作します。しかし、奇妙に思えます。すべての関数のコードはほとんど同じです。そして、すべての関数、特に TaskCanceledException に try/catch を記述する必要があります。ここでキャッチしないと、アプリケーションが終了します。コードを最適化する方法の例を教えてもらえますか?
[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;
}
}