.NET Core 2.1 HttpClient不返回期望值 [英] .NET Core 2.1 HttpClient doesn't return expected values
问题描述
我正在使用接口从此url调用api http://localhost:55260/api/Accounts/GetList
I am using an interface to call an api from this url http://localhost:55260/api/Accounts/GetList
这是其引用的控制器:
[HttpGet]
[Route("GetList")]
[AllowAnonymous]
public ActionResult<IEnumerable<string>> GetList()
{
return new string[] { "value1", "value2" };
}
但是,我得到的不是返回字符串,而是:
However, instead of the strings returning, I'm getting this:
这就是我声明httpclient/interface的方式:
This is how I'm declaring my 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();
I have already declared it in my Startup.cs as services.AddHttpClient();
这就是我所谓的界面
private readonly IAuthenticationClient authenticationClient;
public HomeController(IAuthenticationClient authenticationClient)
{
this.authenticationClient = authenticationClient;
}
public IActionResult Index()
{
var result = authenticationClient.GetData();
return View();
}
我错过了什么吗?或者是否有关于如何使用HttpClients的教程?另外,我该如何通过它发布数据?
Have I missed something or is there a tutorial on how to use HttpClients? Also, how do I post data through this?
推荐答案
您的接口定义了异步调用.换句话说,"GetData"返回的是Task<string>
而不是实际值.
your interface defines an async call. in other words "GetData" returns Task<string>
not that actual value.
为了获得实际值,请尝试以下操作(徒手编写代码,以便进行调试)
In order to get the actual values try this (coding free hand so not debugged)
public async Task<IActionResult> Index()
{
var result = await authenticationClient.GetData();
return View(result);
}
这篇关于.NET Core 2.1 HttpClient不返回期望值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!