Search code examples
c#asp.netapiasp.net-mvc-4actionresult

How to consume a API and return the content in JSON format?


I'm struggling with the following problem:

I've created a solution with the following projects: 1 MVC front-end and 2 test API's for testing my backend API broker.

In my front-end I call my API broker(which is also an API) which sends requests to my 2 test API's. I'm receiving the response of this request in my API Broker in string format and I'm trying to return this into JSON to my front-end, how do I consume this api and return the response in JSON to my front-end? Look code below:

Front-end calling my API Broker:

[HttpGet]
    public async Task<ActionResult> getCall()
    {
        string url = "http://localhost:54857/";
        string operation = "getClients";

        using (var client = new HttpClient())
        {
            //get logged in userID
            HttpContext context = System.Web.HttpContext.Current;
            string sessionID = context.Session["userID"].ToString();

            //Create request and add headers
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Custom header
            client.DefaultRequestHeaders.Add("loggedInUser", sessionID);

            //Response
            HttpResponseMessage response = await client.GetAsync(operation);
            if (response.IsSuccessStatusCode)
            {
                string jsondata = await response.Content.ReadAsStringAsync();
                return Content(jsondata, "application/json");
            }
            return Json(1, JsonRequestBehavior.AllowGet);
        }
    }

My API Broker consuming one of my two test API's:

    [System.Web.Http.AcceptVerbs("GET")]
    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("RedirectApi")]
    public void getCall()
    {
        setVariables();

        WebRequest request = WebRequest.Create(apiUrl);
        HttpWebResponse response = null;
        response = (HttpWebResponse)request.GetResponse();

        using (Stream stream = response.GetResponseStream())
        {
            StreamReader sr = new StreamReader(stream);
            var srResult = sr.ReadToEnd();
            sr.Close();
            //Return JSON object here!

        }
    }

I'm also worried that my front-end is expecting a ActionResult instead of a JSON object, I hope you I find some suggestions here.

Thanks in advance!


Solution

  • use HttpClient for making the request which allows you to read the content as string. Your API needs to be configured so it will allow JSON responses (default behavior) and then here is an example of making a request and reading it as string which will be in JSON format (if the API returns a JSON body).

    HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
    response.EnsureSuccessStatusCode();
    string responseBody = await response.Content.ReadAsStringAsync();
    

    Receiving JSON data back from HTTP request