在 returns json 的 MVC5 ApiController 中设置响应代码
Setting a response code in a MVC5 ApiController that returns json
我有类似这样的使用 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
它工作正常,如您所见,它 returns 在正常和错误情况下都是浏览器的 json 对象。在发生异常的情况下,如何将响应代码设置为 500 以及将 ErrorMessage 作为 json 对象返回?
你可以执行 HttpStatusCodeResult before returning your 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
我有类似这样的使用 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
它工作正常,如您所见,它 returns 在正常和错误情况下都是浏览器的 json 对象。在发生异常的情况下,如何将响应代码设置为 500 以及将 ErrorMessage 作为 json 对象返回?
你可以执行 HttpStatusCodeResult before returning your 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