如何返回http状态代码VB.NET Rest API

编程


我正在为移动应用程序开发人员构建一个 REST API。 我希望他们每次调用我的 API 时首先检查返回的状态是否为 200 或其他状态。 所以我用谷歌搜索并找到了这个链接,它正在处理rest API asp.net的状态代码:
创建 Web API 响应[^]

但我的 Rest API 已经以另一种方式构建了 115 个 webmethods,我无法更改我的所有方法并使它们像这样。 下面是我的 webmethods 构建方式的示例:

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 状态代码并以对象作为响应吗?
感谢您的帮助

我尝试过的:

我已经尝试过这个:

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。那么可能是什么问题呢?

解决方案1

最后我找到了解决方案:

根据 这个链接 我们只需使用“WebFaultException”即可更改 http 状态。 现在还有一个很好的方法来返回已处理的错误:

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

那么状态就会改变,返回的对象就会出错。 就我个人而言,我更喜欢返回对象错误而不是其他任何东西……

干杯:)

コメント

タイトルとURLをコピーしました