0

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.

3
  • Did you mean, How to call another WEB API in asp.net mvc5 from your controller? Commented May 23, 2017 at 8:12
  • There are lots of reference on the internet which explains how you can achieve this. refer this for example levelnis.co.uk/blog/… Commented May 23, 2017 at 8:44
  • Yeah, to call remote api from my project. Commented May 23, 2017 at 11:13

2 Answers 2

1

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;
                        }
                    }
Sign up to request clarification or add additional context in comments.

Comments

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

Response parsing using JSON.NET:

JObject joResponse = JObject.Parse(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.