GET到的WebAPI电话 [英] GET calls to WebAPI

查看:128
本文介绍了GET到的WebAPI电话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML响应到Web API的调用的一个问题。
具体来说,我有一个函数的GetValue打电话,当我要以XML格式为基础,以ID或类Cellulare或类Televisore返回

I have a problem with an XML response to a call to the Web API. Specifically, I have a function "GetValue" call that when I should return in XML format based to the id or class "Cellulare" or class "Televisore".

问题是,如果我从浏览器的要求给了我以下错误:

The problem is that if I make a request from browser gives me the following error:

<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

谁能帮我解决这个问题?

Can anyone help me to solve this problem???

感谢提前
问候
多纳托

Thank in advance greetings Donato

推荐答案

我觉得你的做法是错误的。

I think your approach is wrong.

您有简单的对象返回,可以很容易地通过的WebAPI所提供的默认串行处理。

You have simple objects to return, that can be handled easily by the default serializers webapi has to offer.

您返回的对象类型应该是 IHttpActionResult (webapi2)或的Htt presponseMessage

Your returned object type should be IHttpActionResult (webapi2) or HttpResponseMessage.

我不会去什么@Frank维特认为,造成返回对象本身是不好的做法。特别是在这里你可以通过 IHttpActionResult / 的Htt presponseMessage 返回一个通用对象。

I would NOT go for what @Frank Witte suggested, cause returning the object itself is bad practice. Specifically here you can just return a generic object through 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

这篇关于GET到的WebAPI电话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆