How to call API in asp.net MVC5

2019-09-21 03:53发布

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.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-09-21 04:12

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;
                        }
                    }
查看更多
Rolldiameter
3楼-- · 2019-09-21 04:26
        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);
查看更多
登录 后发表回答