4

In my ASP.NET Core Razor Pages application, I sometimes send requests to the server via ajax.

In those cases, I want to return JsonResult either for success or for error.

But I can't find a way to change HTTP Status Code for JsonResult.

Here's my method:

public IActionResult OnPostFileUpload()
{
   try
   {
       // code to manage and save the file, this request is AJAX
       return new JsonResult("done");
   }
   catch (Exception ex)
   {
       return new JsonResult(message); // how should I set it to be 500?
   }
}
1
  • 2
    Set .StatusCode on the JsonResult object? Commented Dec 23, 2021 at 6:38

1 Answer 1

12

You can assign the StatusCode to JsonResult as below:

using System.Net;
return new JsonResult(message)
{
    StatusCode = (int)HttpStatusCode.InternalServerError
};

References

JsonResult class Properties

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.