I have a web API and i want to get some data in a controller and show on a view.
this is my main class:
public class APISrv
{
public string result = string.Empty;
public async Task<string> GetIT()
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:2474/");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await
client.GetAsync("api/Test/Get");
if (Res.IsSuccessStatusCode)
{
result = Res.Content.ReadAsStringAsync().Result;
}
}
}
catch (Exception err)
{
result=err.Message;
}
return result;
}
}
i tested my class with two controllers:
one:
public ActionResult Index()
{
APISrv aPISrv = new APISrv();
aPISrv.GetIT();
ViewData["mydata"] = aPISrv.result;
return View();
}
in this cause "result" is a public field and always is empty,it seems main thread does not wait for async method done its work.i can see my view but "ViewData["mydata"]" is empty.
on second:
public ActionResult Index()
{
APISrv aPISrv = new APISrv();
ViewData["mydata"] = aPISrv.GetIT().Result;
return View();
}
in this cause my page stay in "waiting for local..." mode and does not work anything.
how can i and what is the best way to get data from my class?