我使用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对象?
您可以在返回jsonresult之前执行httpstatuscoderesult:
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