jsonasp.net-mvc-5asp.net-mvc-controller

Setting a response code in a MVC5 ApiController that returns json


I have something like this using 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

It works fine, and as you can see, it returns a json object to the browser in both normal and error conditions. In the case of the exception, how can I set the response code to 500 as well as returning the ErrorMessage as a json object?


Solution

  • You could execute a 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