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.

2
  • 1
    Review this link Commented Jul 23, 2019 at 5:59
  • Razor pages are more similar to WebForms. For Applications returning json MVC/WebAPI APIs are recommended Commented Jul 23, 2019 at 6:06

1 Answer 1

5

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" } );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.