2

When I used MVC controllers I used "return OK(object);" or "return BadRequest(ErrorMessage)" and such.

How can I achieve this is Razor Pages?

I tried return new JsonResult(object); which works when the status code can be 200. But what if I want to return status code 400 with a JSON error message.

Mahyar Mottaghi Zadeh
  • 1,178
  • 6
  • 18
  • 31
Farish
  • 35
  • 2
  • 5

1 Answers1

4

You can return a JsonResult from a Razor Page handler method, and set the HTTP status code for the response:

public IActionResult OnGet()
{
    Response.StatusCode = 400;
    return new JsonResult(new { message = "Error" } );
}
Mike Brind
  • 28,238
  • 6
  • 56
  • 88