Reputation: 1236
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
Upvotes: 0
Views: 71
Reputation: 247561
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
Upvotes: 1
Reputation: 7285
Just return a Badrequest:
..
If Not dm.dataisvalid then
return BadRequest("Your error message")
End If
Return Ok(dm) 'need to wrap this with Ok
Upvotes: 1