GET调用WebAPI

时间:2015-05-21 10:06:29

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

我对调用Web API的XML响应有问题。 具体来说,我有一个功能" GetValue"当我应该根据id或class" Cellulare"或班级"电视直播"。

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

<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

任何人都可以帮我解决这个问题吗?

提前感谢 问候 多纳托

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-1)

它会抛出错误,因为您没有为GetValue函数提供任何返回类型。你评论说出来了。

正如我从您的代码中可以看出的那样,您将返回一个不同类型的对象,具体取决于您提供给GetValue调用的ID。我不知道你想要做的事情的完整背景,但从我所看到的是,对于不同类型的对象,拥有一个不同的控制器或至少路由会更有意义:

/api/cellulare/<id>

将映射到控制器CellulareController。

/api/televisore/<id>

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

希望这有帮助。

相关问题