Search code examples
jsonasp.net-corehttp-get

How can I customize what GET returns


I want my API to return a custom text before the JSON that it returns. Now it only returns JSON but how can I show another static text before JSON.

Let's say my GET returns me this [{"name":"name"...}] I want to return StaticText [{"name":"name"...}] StaticText"

[HttpGet]
public async Task<ActionResult<IEnumerable<Customers>>> GetCustomers()
{
   return await _context.Customers.ToListAsync();
}

Solution

  • You just need to stringify your result then concatenate the string you want;

    ...
    var yourCustomStr = "I am a custom string!";
    var result = await _context.Customers.ToListAsync();
    var resultStr = JsonConvert.SerializeObject(result);
    return Content($"{resultStr} {yourCustomStr}", "application/json");
    ...