如何在asp.net MVC5中调用API [英] How to call API in asp.net MVC5
本文介绍了如何在asp.net MVC5中调用API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个asp.net mvc5项目,我想使用JSON调用另一个API, 而且我想从Controller动作中调用该API,因为我需要在其中进行一些哈希处理,
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,
这是我第一次这样做,我需要使用JSON操作以JSON格式发送请求,并使用JSON响应来获取响应.
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.
推荐答案
如果您的方法是POST:
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();
如果您的方法是GET:
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;
}
}
这篇关于如何在asp.net MVC5中调用API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文