简体   繁体   English

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

[英]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.在我的 ASP.NET Core Razor Pages 应用程序中,我有时会通过 ajax 向服务器发送请求。

In those cases, I want to return JsonResult either for success or for error.在这些情况下,我想为成功或错误返回JsonResult

But I can't find a way to change HTTP Status Code for JsonResult .但是我找不到更改 JsonResult 的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:您可以将 StatusCode 分配给JsonResult ,如下所示:

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

References参考

JsonResult class Properties JsonResult class 属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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