如何将这些代码更改为c#风格
本文关键字:风格 代码 | 更新日期: 2023-09-27 18:13:56
这是我的HttpService类,它工作正常。但是看起来很奇怪,每个函数中的代码都差不多。我应该在每个函数中写try/catch,特别是TaskCanceledException,如果我不在这里捕获它,我的应用程序将终止。谁能给我举个例子,告诉我如何优化代码?
[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;
}
}
如果我没有在这里捕获它,我的应用程序将终止。
不,那根本不是真的;正是调用的代码才有机会(实际上是责任)处理错误。例如:
try {
var permission = await getPermission();
//...
} catch(Exception ex) {
// log, whatever
}
将异常处理放在最合适的位置将减少async
方法中不必要的代码。当前所做的是使您的async
方法假装没有发生任何坏事-这不是这里的最佳实践。
免责声明:我不能编译这个,所以你可能需要修改一下。
我认为你唯一能做的就是创建一个这样的方法:
public async Task<T> getAsync(string url)
{
try
{
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<T>();
return (T)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<User>> getUsers()
{
return await getAsync("api/User");
}
public async Task<IEnumerable<permission>> getPermission()
{
return await getAsync("api/User");
}
public async Task<CurrentUser> getCurrentUserInfo(User user)
{
return await getAsync("api/User?name=" + user.Name);
}