开发者

XML generation in ASP.NET 2.0 web services?

开发者 https://www.devze.com 2023-02-21 08:05 出处:网络
I\'m building a web service (.asmx) with ASP 2.0, and a lot of my methods return custom objects.It\'s always converted my objects into XML for me using the properties of the objects, but I\'ve run int

I'm building a web service (.asmx) with ASP 2.0, and a lot of my methods return custom objects. It's always converted my objects into XML for me using the properties of the objects, but I've run into a situation where it doesn't.

I need to return a bunch of objects of different classes at once, and the classes are unfortunately not related through inheritance, so I'm returning an array of objects from my web method. The output looks like this:

<ArrayOfAnyType>
<anyType xsi:type="Type1"/>
<anyType xsi:type="Type2"/>
</ArrayOfAnyType>

The Type1 and Type2 classes have properties defined, but they're not auto-implemented, and they're read only. All properties I've seen auto-converted into XML so far have been fully auto-implemented. Is this why it doesn't convert properly? Am I going to have to redesign my classes to get this to work, or is there an attribute I can add somewhere, or an interface I can implement, or something like that?

My class declarations look like this:

Public Class Type1
    Dim _var1 As Decimal

    Public Sub New()
        Dim conn As New SqlConnection(ConfigurationManager.AppSettings("myString"))
        conn.Open()
        Dim command As New SqlCommand("SELECT * FROM table1", conn)
   开发者_JAVA技巧     Dim reader As SqlDataReader = command.ExecuteReader()
        reader.Read()
        _var1 = reader("Var1")
        reader.Close()
        conn.Close()
    End Sub

    Public ReadOnly Property Var1() As Decimal
        Get
            Return _var1
        End Get
    End Property
End Class

EDIT: clarifying my question: why is the XML serialization process ignoring my properties in this class? Because they're not auto-implemented? Or because they're read only? Or something else?


XML Serialization only works with public, read/write properties. Sorry, but your read-only properties will never be serialized.


ASP.NET 2.0 web services run off the XML Serializer in System.Xml.Serialization (if memory serves) and the related attributes there such as XmlIgnore().

Unfortunately, getting that to work with a polymorphic collection can be a bit of a trick. If it is a limited number of classes, the easiest way out would be to do something like:

public class Shelf
{
    public Bottle[] Bottles {get; set;}
    public Box[] Boxes {get; set;}
}

It might be worth looking at WCF here, it has much better options.

0

精彩评论

暂无评论...
验证码 换一张
取 消