【问题标题】:GET calls to WebAPI对 WebAPI 的 GET 调用
【发布时间】:2015-08-02 22:28:08
【问题描述】:

我遇到了对 Web API 调用的 XML 响应问题。 具体来说,我有一个函数“GetValue”调用,当我应该基于 id 或类“Cellulare”或类“Televisore”以 XML 格式返回时。

问题是,如果我从浏览器发出请求,则会出现以下错误:

<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>

这是一个例子:

Public Class Cellulare
    Public Property Colore As String
    Public Property SistemaOperativo As String
End Class

Public Class Televisore
    Public Property Colore As String
    Public Property Marca As String
End Class          

Public Function GetValue(ByVal id As Integer) // ' As Cellulare
    If Id = 1 Then    
        Dim MyTelevisore As New Televisore    
        MyTelevisore.Colore = "grigio"
        MyTelevisore.Marca = "lg"
        Return MyTelevisore
    Else            
        Dim MyCellulare As New Cellulare    
        MyCellulare.Colore = "nero"
        MyCellulare.SistemaOperativo = "android"    
        Return MyCellulare
    End If    
End Function

谁能帮我解决这个问题???

提前致谢 你好 多纳托

【问题讨论】:

    标签: asp.net xml vb.net asp.net-web-api


    【解决方案1】:

    我认为你的方法是错误的。

    您有简单的对象要返回,可以通过 webapi 必须提供的默认序列化程序轻松处理。

    您返回的对象类型应为IHttpActionResult (webapi2) 或HttpResponseMessage

    我不会按照@Frank Witte 的建议去做,因为返回对象本身是不好的做法。具体来说,您可以通过IHttpActionResult / HttpResponseMessage 返回一个通用对象。

    你应该这样做:

    Public Function GetValue(ByVal id As Integer) As IHttpActionResult
        If Id = 1 Then    
            Dim MyTelevisore As New Televisore    
            MyTelevisore.Colore = "grigio"
            MyTelevisore.Marca = "lg"
            Return Ok(MyTelevisore)
        Else            
            Dim MyCellulare As New Cellulare    
            MyCellulare.Colore = "nero"
            MyCellulare.SistemaOperativo = "android"    
            Return Ok(MyCellulare)
        End If    
    End Function
    

    【讨论】:

    • 非常感谢您的回答。这就是我想要的。我尝试了您建议的示例并且它有效。
    • 出现此警告:投票需要 15 声望!我有 6 个声望。
    【解决方案2】:

    它会引发错误,因为您没有为 GetValue 函数提供任何返回类型。你把它注释掉了。

    从您的代码中我可以看出,您返回的对象类型不同,具体取决于您提供给 GetValue 调用的 id。我不知道您要做什么的完整上下文,但据我所知,为不同类型的对象使用不同的控制器或至少路由会更有意义:

    /api/cellulare/<id>
    

    将映射到控制器 CellulareController。

    /api/televisore/<id>
    

    将映射到控制器 TelevisoreController。如果你愿意,每个都有自己的 Get()、Post() 和 Delete() 方法。

    希望这会有所帮助。

    【讨论】:

    • 你确定是这个原因吗?
    • 您可以通过显式设置函数的返回类型来测试它。
    • 我认为这种方法是不好的做法。应该返回一些通用对象,例如IHttpActionResult / HttpResponseMessage
    • 是的,这样更好。我的观点是您根本没有定义返回类型,并且在 XML 中不能很好地序列化。因此出现错误消息。
    • 好吧,也许你在技术上是对的,但我认为@BlackThunder 在这里需要一个更有建设性的答案......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2017-01-28
    • 2023-03-17
    • 2013-12-25
    相关资源
    最近更新 更多