Web API 2服务 - 如何在模型对象期望时返回错误消息?

时间:2016-09-21 19:29:53

标签: .net vb.net controller asp.net-web-api2

所以我在我的控制器中创建了一个GetValues函数来返回demoModel的实例,这是一个复杂的模型类。

返回成功的数据集时可以正常工作。但是,如果某些内容无法验证当函数需要demoModel对象时如何将消息发送回调用方?

这是控制器代码:

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

2 个答案:

答案 0 :(得分:1)

回到Badrequest:

..
            If Not dm.dataisvalid then
                return BadRequest("Your error message")
            End If

            Return Ok(dm) 'need to wrap this with Ok

答案 1 :(得分:1)

将函数返回类型从模型更改为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

在调用函数时,响应消息将在其有效负载中具有必要的上下文信息。

阅读Action Results in Web API 2,了解有关行动结果的更多详情