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?
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.
In case you use System.Net
Dim statsText As String = httpResponse.StatusCode
MsgBox(statsText)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.