【问题标题】:How to return JsonResult with HTTP Status Code 500 from Razor Page?如何从 Razor 页面返回带有 HTTP 状态代码 500 的 JsonResult?
【发布时间】:2022-01-24 05:37:36
【问题描述】:

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

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

但我找不到更改 JsonResult 的 HTTP 状态代码的方法。

这是我的方法:

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

【问题讨论】:

  • JsonResult 对象上设置.StatusCode

标签: c# asp.net-core razor-pages


【解决方案1】:

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

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

参考文献

JsonResult class Properties

【讨论】:

    猜你喜欢
    • 2019-10-19
    • 2019-07-15
    • 1970-01-01
    • 2016-09-16
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多