【问题标题】:Return HTTP status code using REST API使用 REST API 返回 HTTP 状态码
【发布时间】:2017-06-13 13:07:26
【问题描述】:

我们如何使用 VB.NET Framework 4.0 返回 HTTP 状态代码以及 REST API 中返回的对象?

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

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,我不知道为什么。

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

【问题讨论】:

  • 您是否尝试过捕获HttpException 并询问内部异常?
  • 没有例子吗?以及为什么他们没有在其他模板中捕捉到它
  • 好吧,我不能说为什么它不会在其他模板中引起异常 (??)。但是简单地说,您正在与服务器通信,它知道您正在与它通信,但它无法理解您的请求,因此出现 400 异常。捕获异常应该提供有关什么导致问题的更多信息。
  • 但如果我添加 catch 状态变为 200

标签: vb.net rest httpresponse http-status-codes


【解决方案1】:

终于找到了解决办法:

根据this link,我们只需要使用'WebFaultException' 来改变http 状态。现在还有一个很好的方法来返回已处理的错误:

公共函数TestMethod2(ByVal name As 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 之间的差异),我个人更喜欢返回我创建的对象错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 2011-11-09
    • 2013-12-04
    • 1970-01-01
    相关资源
    最近更新 更多