Manish Tiwari Manish Tiwari - 4 months ago 22
JSON Question

How to consume Web Api based on Json using Asp MVC 5?

I am new in Asp Mvc so i have no idea how to do this ?

i am using an recharge api so i want to pass some data in url and want to get back response.

if i run this web api url in browser recharge successfully to on respectively mobile number. so i want to get recharge successfully or not.

Api Url :

https://www.example.com/recharge?api_token=token&number=123456789&amount=10


Code :

public ActionResult Recharge()
{
string url =
"https://www.example.com/recharge?api_token=token&number=123456789&amount=10";
client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = ConsumeApi(2);
return View();
}

public async Task<String> ConsumeApi(int id)
{
HttpResponseMessage responseMessage = await client.GetAsync(url);
if (responseMessage.IsSuccessStatusCode)
{
var responseData = responseMessage.Content.ReadAsStringAsync().Result;

return responseData;
}
return "wrong";
}

Answer

Have you tried to await the call to consumeApi? Because this is async your view is potentially returned before the call completes

client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await ConsumeApi(2);
return Json(response);

I changed your response to json so you could inspect the respons in the browser when you call your method.

Comments