我如何返回http状态代码VB.NET rest API [英] How do I return http status code VB.NET rest API
问题描述
我正在为移动应用开发者构建一个rest API。我希望他们每次调用我的API时首先检查返回的状态是否为200或其他。所以我用Google搜索并发现此链接正在处理其余API asp.net的状态代码:
创建Web API响应 [ ^ ]
但是我的Rest API已经构建了115个webmethods的另一种方式,我无法改变我的所有方法并使它们像这样。下面是我的web方法的构建示例:
I am building a rest API to mobile apps developers. I want them each time they call my APIs to check first if the returned status is 200 or something else. So I googled and found this link which is handling status codes of rest API asp.net:
create Web API response[^]
But my Rest API is already built an another way with 115 webmethods and I cannot change all my methods and make them like this. Below is an example of how my webmethods are built:
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
' Do something else
Finally
InfoAndTerms = result
End Try
End Function
其中'InfoAndTerms'是'DataTypes'模块中的结构
所以我的问题是:是否有任何其他方法返回http状态代码与对象作为响应?
感谢您的帮助
我尝试过的事情:
我试过这个:
Where 'InfoAndTerms' is a Structure in a 'DataTypes' module
So my question is: isn't there any other way to return http status code with object as response?
Your helps are appreciated
What I have tried:
I have tried this :
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
但是当我测试这种方法时,我得到状态400而不是500.那么可能是什么问题?
But when I tested this method I got status 400 instead of 500. SO what could be the problem?
推荐答案
最后我找到了一个解决方案:
根据这个链接我们只需要使用'WebFaultException'来改变http状态。现在还有一个很好的方法来返回处理的错误:
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
然后状态将改变,返回的对象将是一个错误。我个人更喜欢返回对象错误而不是其他任何东西...
干杯:)
Then the status will change and the returned object will be an error. Personally I prefer to return object error instead of anything else ...
Cheers :)
这篇关于我如何返回http状态代码VB.NET rest API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!