我将使用界面调用此URL的API http://localhost:55260/api/Accounts/GetList。
这是它所引用的控制器:
然而,我得到的不是字符串返回值,而是这个: 这是我声明httpclient/interface的方式:
这是它所引用的控制器:
[HttpGet]
[Route("GetList")]
[AllowAnonymous]
public ActionResult<IEnumerable<string>> GetList()
{
return new string[] { "value1", "value2" };
}
然而,我得到的不是字符串返回值,而是这个: 这是我声明httpclient/interface的方式:
private readonly HttpClient httpClient;
public AuthenticationClient(HttpClient httpClient)
{
httpClient.BaseAddress = new Uri("http://localhost:55260/api/Accounts");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
this.httpClient = httpClient;
}
public async Task<IEnumerable<string>> GetDataAsync()
{
List<string> result = null;
HttpResponseMessage response = await httpClient.GetAsync("/GetList");
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsAsync<List<string>>();
}
return result;
}
我已经在我的Startup.cs中声明了它,使用services.AddHttpClient();
这是我调用接口的方式
private readonly IAuthenticationClient authenticationClient;
public HomeController(IAuthenticationClient authenticationClient)
{
this.authenticationClient = authenticationClient;
}
public IActionResult Index()
{
var result = authenticationClient.GetData();
return View();
}
我是否错过了什么或者有关于如何使用HttpClients的教程?另外,我该如何通过它来发布数据?