Off The Gold Off The Gold - 2 months ago 21
Vb.net Question

Web API 2 Service - how to return error message when model object expected?

So I have created a

GetValues
function in my controller to return the instance of a
demoModel
which is a complex model class.

This works fine when returning a successful data set. However if something doesn't validate how do I send a message back to the caller when the function expects the
demoModel
object?

Here is the controller code:

Namespace Controllers
Public Class GetMyData
Inherits ApiController

'Note always expect 3 values coming in per the WebApiConfig
Public Function GetValues(ByVal age As String, ByVal state As String, ByVal country As String) As demoModel

Dim dm As New demoModel()
Dim myData As New createDemoData

dm = myData.getTotalData(age,state,country)
If Not dm.dataisvalid then
'TODO Send Error message to the user
End If

Return dm

End Function

End Class
End Namespace

Answer

Change the function return type from your model to IHttpActionResul

Namespace Controllers
    Public Class GetMyData
        Inherits ApiController

        Public Function GetValues(ByVal age As String, ByVal state As String, ByVal country As String) As IHttpActionResult

            Dim dm As New demoModel()
            Dim myData As New createDemoData

            dm = myData.getTotalData(age, state, country)
            If Not dm.dataisvalid Then
                return BadRequest("Return invalid data message to caller")  
            End If

            Return Ok(dm) 'return Ok (200) response with your model in the body

        End Function

    End Class
End Namespace

When calling the function the the response message will have the necessary contextual information in its payload.

Read up on Action Results in Web API 2 for more details on action results