如何从 Razor 页面返回 HTTP 状态代码 500 的 JsonResult?

Ali*_*EXE 0 c# asp.net-core razor-pages

在我的 ASP.NET Core Razor Pages 应用程序中,我有时会通过 ajax 向服务器发送请求。

在这些情况下,我想返回JsonResult成功或错误。

但我找不到更改JsonResult.

这是我的方法:

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?
   }
}
Run Code Online (Sandbox Code Playgroud)

Yon*_*hun 8

您可以将 StatusCode 分配给JsonResult如下:

using System.Net;
Run Code Online (Sandbox Code Playgroud)
return new JsonResult(message)
{
    StatusCode = (int)HttpStatusCode.InternalServerError
};
Run Code Online (Sandbox Code Playgroud)

参考

JsonResult 类属性