How to return Raw JSON from API Controller

Today in this article, we shall see how to return Raw JSON from .NET API Controller.

Recently I had requirements to return raw string output acquired from Kafka. The string was a typical ASCII format with “” and escape character to deal with.

Example

"[{\"FirstName\": \"ABCD\",
\"LastName\": \"TEST\",
\"EmployeeId\": \"1111\",
\"Address\": [{\"ZipCode\": \"1234\",
\"State\": \"CA\",
\"Country\":\"USA\"}}]]";

Above response, I was able to return using Content class.

public async Task<ActionResult> GetSalary(string id)
        {
            dynamic result =null;
            try
            {
                if (id==null)
                {
                    return BadRequest("Invalid input");
                }
                 result = await _employeeRepository.GetEmployeesNew(id);

                if (result == null)
                {
                    return NotFound("No resource or record found");
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                //Log error using Ilogger
            }

            return Content(result, "application/json");
        }

Below shows the response in Postman for the above JSON data,

return Raw JSON

References:

That’s all! Happy coding!

Does this help you fix your issue?

Do you have any better solutions or suggestions? Please sound off your comments below.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



4 thoughts on “How to return Raw JSON from API Controller

  1. Thank you very much! You are the single one that presents an actual solution for the problem:
    return Content(res.ToString(), “application/json”);

    My target was to create a proxy api that will return dynamic responses. And you gave me a solution!

    Fantastic!

Leave a Reply

Your email address will not be published. Required fields are marked *