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,
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.
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!
Thanks Lev.Glad to know solution helped you !!
Thank you very much! I googled and tried different solutions for two hours before I found this.
Hey Halvard- Thanks for your comments. Glad it helped you!