I have asp.net mvc5 project that I want to call another API using JSON,
and I want to call that API from my Controller action because I need to do some hashing in there,
It's my first time doing this, and I need to send the request in JSON and also get responses in JSON all of that using the controller action.
If your method is POST :
string uri = "yourdomain/api/controller/method;
var client = new HttpClient();
var values = new Dictionary<string, string>()
{
{"username", SecurityHelper.EncryptQueryString(username)},
{"password", SecurityHelper.EncryptQueryString(password)},
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
If your method is GET :
string url = "domain/api/controller/method?parameter1=param";
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var jsonResponse = response.Content.ReadAsStringAsync().Result;
bool data = JsonConvert.DeserializeObject<bool>(jsonResponse);
return data;
}
}
var client = new HttpClient();
var payload = @"{
'CPU': 'Intel',
'PSU': '500W',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive',
'200 gigabype hard drive'
]
}";
var content = new StringContent(payload, Encoding.UTF8, "application/json");
var url = {APIEndpoint};
var result = await client.PostAsync(url, content);
Response parsing using JSON.NET:
JObject joResponse = JObject.Parse(result);