我有这种反复出现的方法,我需要转换为通用方法。我正在使用.net core 2.0,我正在创建一组调用远程API的新API。我将在角度前端使用结果数据,并启用远程API无法提供的身份验证和授权。重复代码类似于ff:
[HttpGet("getAddressBook")]
public async Task<IActionResult> GetAddressBook()
{
string BaseURL = Configuration.GetSection("AppSettings:BaseURL").Value;
AddressBookRootObject AddressBookInfo = new AddressBookRootObject();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BaseURL);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await client.GetAsync("/v1/addressBook_get");
if (Res.IsSuccessStatusCode)
{
var ParametersResponse = Res.Content.ReadAsStringAsync().Result;
AddressBookInfo = JsonConvert.DeserializeObject<AddressBookRootObject>(ParametersResponse);
}
else
{
return BadRequest("Error retrieving data from server");
}
return Ok(AddressBookInfo.data);
}
}
我对此代码没有任何问题,它运行完美但我需要将其转换为通用方法,因为我有大量使用上述代码的远程API调用。我查看了这个链接:
Converting Method to Generic Method?
但我无法弄清楚如何转换
AddressBookRootObject AddressBookInfo = new AddressBookRootObject();
到通用的。任何帮助都非常感谢。 TIA。
答案 0 :(得分:1)
创建所需功能的简单Web服务抽象
public interface IHttpClient {
Task<T> GetAsync<T>(string uri);
}
使用实现封装操作中的常用功能。
public class WebService: IHttpClient {
private readonly HttpClient client;
public WebService(IConfiguration configuration) {
string BaseURL = configuration.GetSection("AppSettings:BaseURL").Value;
client = new HttpClient();
client.BaseAddress = new Uri(BaseURL);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<T> GetAsync<T>(string url) {
var result = default(T);
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode) {
var json = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<T>(json);
}
return result
}
}
控制器将注入服务并重构操作
private readonly IHttpClient client;
public AddressBookController(IHttpClient client) {
this.client = client;
}
[HttpGet("getAddressBook")]
public async Task<IActionResult> GetAddressBook() {
var AddressBookInfo = await client.GetAsync<AddressBookRootObject>("/v1/addressBook_get");
if (AddressBookInfo != null) {
return Ok(AddressBookInfo.data);
} else {
return BadRequest("Error retrieving data from atCom server");
}
}
可以根据需要更新抽象以包含更多常用功能。
最后确保在服务器集合中注册了抽象和实现。
services.AddSingleton<IHttpClient, WebService>();