如何在asp.net MVC5中调用API

时间:2017-05-23 08:05:37

标签: c# json asp.net-mvc-5 asp.net-web-api2

我有asp.net mvc5项目,我想用JSON调用另一个API, 我想从我的Controller操作中调用该API,因为我需要在那里进行一些散列,

这是我第一次这样做,我需要用JSON发送请求,并使用控制器操作在JSON中获取所有响应。

2 个答案:

答案 0 :(得分:1)

如果您的方法是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:

                    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;
                        }
                    }

答案 1 :(得分:0)

        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);

使用JSON.NET进行响应解析:

JObject joResponse = JObject.Parse(result);