ASP.NET Core by Patrik

Return JSON in ASP.NET Core

The following sample will return JSON with a 200 OK status code (it's an Ok type of ObjectResult)

public IActionResult GetAsJson()
{
   return new OkObjectResult(new Catagory { Id = 1234, Name = "Articles" });
}

The following code uses the Produces() attribute (which is a ResultFilter) with contentType = application/json

[Produces("application/json")]
public Student GetWithProduces()
{
    return new Catagory { Id = 1234, Name = "Articles" };
}

Return JSON with a 400 error code with a message

public IActionResult ErrorJSON()
{
    return new JsonResult(new { message = "The Error Messages" })
    {
StatusCode = StatusCodes.Status400BadRequest // Status code here 
    };
}
JSON
ASP.NET Core

Comments

Leave a Comment

All fields are required. Your email address will not be published.