Reputation: 3024
I am using an interface to call an api from this url http://localhost:55260/api/Accounts/GetList
This is the controller its referencing:
[HttpGet]
[Route("GetList")]
[AllowAnonymous]
public ActionResult<IEnumerable<string>> GetList()
{
return new string[] { "value1", "value2" };
}
However, instead of the strings returning, I'm getting this:
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;
}
I have already declared it in my Startup.cs as services.AddHttpClient();
This is how I call the interface
private readonly IAuthenticationClient authenticationClient;
public HomeController(IAuthenticationClient authenticationClient)
{
this.authenticationClient = authenticationClient;
}
public IActionResult Index()
{
var result = authenticationClient.GetData();
return View();
}
Have I missed something or is there a tutorial on how to use HttpClients? Also, how do I post data through this?
Upvotes: 4
Views: 888
Reputation: 319
ASP.NET Core 2.1 includes a new IHttpClientFactory
service that makes it easier to configure and consume instances of HttpClient
in apps. HttpClient
already has the concept of delegating handlers that could be linked together for outgoing HTTP requests. The factory:
For more information, see Initiate HTTP Requests.
Upvotes: 0
Reputation: 20106
I make it when I change controller code to
public async Task<IActionResult> Index()
{
var result = await _authenticationClient.GetDataAsync();
return View();
}
Modify GetDataAsync()
HttpResponseMessage response = await httpClient.GetAsync("/api/Accounts/GetList");
Upvotes: 0
Reputation: 5791
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);
}
Upvotes: 4