在返回json的MVC5 ApiController中设置响应代码

时间:2018-02-05 16:02:37

标签: json asp.net-mvc-5 asp.net-mvc-controller

我使用MVC5有这样的东西:

Namespace Controllers
Public Class WorkflowsController Inherits ApiController

    <HttpPost>
    <ActionName("SaveComment")>
    Public Function PostComment(id As String, Optional comment As String = "")
        Try
            Dim status As ApiResponse = SomeClass.AddComment(id, comment)

            Return Me.Json(status)
        Catch ex As Exception
            Return Me.Json(New ApiResponse With {.ErrorMessage = ex.Message})
        End Try
    End Function    
End Class
End Namespace

它工作正常,正如您所看到的,它在正常和错误条件下都将json对象返回给浏览器。在异常的情况下,如何将响应代码设置为500以及将ErrorMessage作为json对象返回?

1 个答案:

答案 0 :(得分:1)

您可以在返回HttpStatusCodeResult之前执行JsonResult

    Try
        Dim status As ApiResponse = SomeClass.AddComment(id, comment)

        Return Me.Json(status)
    Catch ex As Exception
        (New HttpStatusCodeResult(500)).ExecuteResult(ControllerContext)
        Return Me.Json(New ApiResponse With {.ErrorMessage = ex.Message})
    End Try