简体   繁体   中英

How to return JsonResult with HTTP Status Code 500 from Razor Page?

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?
   }
}

You can assign the StatusCode to JsonResult as below:

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

References

JsonResult class Properties

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM