0

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!

NielsStenden
  • 357
  • 1
  • 6
  • 25
  • 1
    if you are `kinda new` to asp.net mvc i would suggest a tutorial or book on some of the fundamentals would be of more benefit that trying to get people to write code for you on this forum. – jazb May 01 '19 at 07:28

1 Answers1

0

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

Jamie Lupton
  • 118
  • 8
  • Hi, what return type i make my method? It's void now. – NielsStenden May 01 '19 at 08:54
  • Hi, what return type i make my method? It's void now. Also this method is returning a string which adds "/" to my content for escaping? How can i prevent this and just return a JSON object? – NielsStenden May 01 '19 at 09:08
  • use Newtonsoft to de-serialize the data. If the object type changes i.e. you are calling different endpoints then you will need to use generics to specify the type. But if you know that the type won't change then you can do something like this: return JsonConvert.DeserializeObject(stringContent) – Jamie Lupton May 01 '19 at 13:08