A.Rowan
A.Rowan

Reputation: 1749

Pass a json object through .net core api

I am trying to call an endpoint providing a Json Object from an api and then return that object unchanged.

I've tried this:

using(var client = new HttpClient())
    {
        var response = await client.GetAsync(new Uri($"RestEndpoint"));

        return Ok(response.Content.ReadAsStringAsync());

    }

and this:

using(var client = new HttpClient())
    {
        var response = await client.GetAsync(new Uri($"RestEndpoint"));
        var stream = await response.Content.ReadAsStreamAsync();
        byte[] buffer = new byte[32768];
        using (MemoryStream memoryStream = new MemoryStream())
        {
            while (true)
            {
                int read = stream.Read(buffer, 0, buffer.Length);
                if (read <= 0)
                {
                    return Ok( memoryStream.ToArray());
                }
                memoryStream.Write(buffer, 0, read);
            }
        }
    }

But neither provides the JSON object as the HttpClient receives it. I say that because when I hit the endpoint with Postman it's in the correct format.

Background: I have a http trigger function app providing a json object, it's effectively acting like an api endpoint. I'm using this function app because the model is already present in my function app project. However there is a separate api for our project which has all of the authentication / authorization in place. So I need to call the existing function app endpoint from the api and pass the Json object directly through without deserializing and parsing it to an object. I don't want to have a copy of the model in the api project.

Upvotes: 1

Views: 231

Answers (1)

Mikhail Shilkov
Mikhail Shilkov

Reputation: 35124

Replace your Ok call with

var content = await response.Content.ReadAsStringAsync();
return Content(content, "application/json");

Content method returns the given string as-is.

Upvotes: 1

Related Questions