C# How can I return my base class in a webservice

Posted by HenriM on Stack Overflow See other posts from Stack Overflow or by HenriM
Published on 2010-05-12T11:49:49Z Indexed on 2010/05/12 11:54 UTC
Read the original article Hit count: 249

Filed under:
|
|
|
|

I have a class Car and a derived SportsCar: Car
Something like this:

public class Car
{
    public int TopSpeed{ get; set; }
}


public class SportsCar : Car
{
    public string GirlFriend { get; set; }
}

I have a webservice with methods returning Cars i.e:

[WebMethod]
public Car GetCar()
{
    return new Car() { TopSpeed = 100 };
}

It returns:

<Car>
<TopSpeed>100</TopSpeed>
</Car>

I have another method that also returns cars like this:

[WebMethod]
public Car GetMyCar()
{
    Car mycar = new SportsCar() { GirlFriend = "JLo", TopSpeed = 300 };
    return mycar;
}

It compiles fine and everything, but when invoking it I get:
System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type wsBaseDerived.SportsCar was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

I find it strange that it can't serialize this as a straight car, as mycar is a car.

Adding XmlInclude on the WebMethod of ourse removes the error:

[WebMethod]
[XmlInclude(typeof(SportsCar))]
public Car GetMyCar()
{
    Car mycar = new SportsCar() { GirlFriend = "JLo", TopSpeed = 300 };
    return mycar;
}

and it now returns:

<Car xsi:type="SportsCar">
    <TopSpeed>300</TopSpeed>
    <GirlFriend>JLo</GirlFriend>
</Car>

But I really want the base class returned, without the extra properties etc from the derived class.

Is that at all possible without creating mappers etc?

Please say yes ;)

© Stack Overflow or respective owner

Related posts about c#

Related posts about webservice