在返回json的MVC5 ApicController中设置响应代码
我在使用MVC5时有类似的功能:在返回json的MVC5 ApicController中设置响应代码,json,asp.net-mvc-5,asp.net-mvc-controller,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
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对象返回?您可以在返回之前执行:
这是一个C版本,删除X-Requested-With标头的if条件,它应该适用于所有请求如果您的ApiResponse已经处理了错误消息,为什么返回500响应代码?
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