0
我是新的Asp Mvc,所以我不知道如何做到這一點?如何使用基於JSON的Web API使用Asp MVC 5?
我正在使用充電API,所以我想通過一些數據在URL中,並希望得到迴應。
如果我在瀏覽器中運行此web api url成功地分別對手機號碼進行充值。所以我想要成功或不是充值。
API網址:
https://www.example.com/recharge?api_token=token&number=123456789&amount=10
代碼:
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";
}
Thanks @Jras it's working –