gpt4 book ai didi

c# - 如何将这些代码更改为 C# 样式?

转载 作者:行者123 更新时间:2023-11-30 13:58:31 24 4
gpt4 key购买 nike

<分区>

这是我的 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;
}

}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com