0

How do we return a HTTP status code with the object returned in REST API using VB.NET Framework 4.0?

I have Googled this and found some solutions like throwing the error before returning the object as below:

Public Function InfoAndTerms(ByVal Lang As String) As Information() Implements IService.InfoAndTerms

Dim result() As Information    
Try
    ' Do something and fill result
Catch ex As Exception
    Throw New System.Web.HttpException(500, "Error - InfoAndTerms")
Finally  
        InfoAndTerms = result
End Try   

End Function

But in my case this function is always returning status 400 instead of 500 and I don't know why.

How do I fix this problem? Is there any other way to do that?

Belisarius
  • 21
  • 5
Mlle 116
  • 1,149
  • 4
  • 20
  • 53
  • Have you tried catching the `HttpException` and interrogating the inner exception? – IronAces Jun 12 '17 at 13:04
  • isn't there any example? and why they are not catching it in other templates – Mlle 116 Jun 12 '17 at 13:12
  • Well, I can't say why it isn't causing an exception in other templates (??). However simply put, you're communicating with a server, it knows you're communicating with it, but it can't understand your request, hence the 400 exception. Catching the exception should provide more information on _what_ is causing the problem. – IronAces Jun 12 '17 at 13:16
  • But if I add catch the status becomes 200 – Mlle 116 Jun 12 '17 at 13:27

2 Answers2

0

Finally I found a solution:

According to this link we just have to use 'WebFaultException' which will change the http status. Now there is also a nice method to return the handled error :

Public Function TestMethod2(ByVal name As String) As String Implements IService.TestMethod2

If name = "" Then

    Dim str As New ErrMessage
    str.intErr = 1
    str.strErrMessage = "bla bla bla"

    Throw New WebFaultException(Of ErrMessage)(str, HttpStatusCode.BadRequest)

End If

Return name

End Function

the returned status here will be 400 (try to change bad request to something else and you will see the difference between returned status num) and personally I prefer to return object Error that I created.

Mlle 116
  • 1,149
  • 4
  • 20
  • 53
0

In case you use System.Net

Dim statsText As String = httpResponse.StatusCode
MsgBox(statsText)
Abd Domingos
  • 55
  • 1
  • 13