2016-09-21 48 views
0

所以我在我的控制器中创建了一个GetValues函数来返回一个demoModel这是一个复杂的模型类的实例。Web API 2服务 - 如何在模型对象预期时返回错误消息?

这在返回成功的数据集时正常工作。但是,如果某些东西不能验证当函数期望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 

回答

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的行动更多的细节导致

+0

这就是我所缺少的。这工作完美,并感谢链接。 –

1

只返回一个错误请求:

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

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

我尝试这样做,但我得到一个错误信息:类型的值“BadRequestErrorMessageResult”不能转换为demoModel。预期的返回类型是demoModel –