繁体   English   中英

使用 REST API 返回 HTTP 状态码

[英]Return HTTP status code using REST API

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

我已经用谷歌搜索了这个并找到了一些解决方案,例如在返回 object 之前抛出错误,如下所示:

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

但在我的情况下,这个 function 总是返回状态 400 而不是 500,我不知道为什么。

我该如何解决这个问题? 有没有其他方法可以做到这一点?

终于我找到了解决方案:

根据此链接,我们只需要使用“ WebFaultException”即可更改http状态。 现在,还有一种不错的方法可以返回已处理的错误:

公共函数TestMethod2(ByVal名称为String)As String实现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

结束功能

返回的状态为400(尝试将错误的请求更改为其他请求,您将看到返回状态num之间的差异),我个人更喜欢返回我创建的对象Error。

如果您使用 System.Net

Dim statsText As String = httpResponse.StatusCode
MsgBox(statsText)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM