Subclass Contracts

Topics: Web Api
Nov 14, 2011 at 7:06 PM

There must be a simple solution to this problem.  The following is the complete code for a webapi "Blah" service.  It should return either a BlahEntity or a MyBlahEntity, depending on the Url passed.

Everytime I try to return MyBlahEntity, the service crashes.  

 

using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web.Routing;

namespace TestWebAPI
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.MapServiceRoute("Blah");
        }
    }

    [ServiceContract]
    public class BlahService
    {
        [WebGet(UriTemplate = "/Get1/{id}")]
        public BlahEntity Get1(int id)
        {
            return new BlahEntity { Id = id };       // This works
        }

        [WebGet(UriTemplate = "/Get2/{id}")]
        public BlahEntity Get2(int id)
        {
            return new MyBlahEntity { Id = id, Name = "MyBlah"};    // This doesn't
        }
    }

    [DataContract]
    [KnownType(typeof(MyBlahEntity))]
    public class BlahEntity
    {
        [DataMember]
        public int Id { get; set; }
    }

    [DataContract]
    public class MyBlahEntity : BlahEntity
    {
        [DataMember]
        public string Name { get; set; }
    }

}
Nov 15, 2011 at 5:34 PM

    public class BlahEntity
    {
        public int Id { get; set; }
    }

    public class MyBlahEntity : BlahEntity
    {
        public string Name { get; set; }
    }

Is the class definitions I used and it works fine, I took your code for the urls and used those.

Admittedly I use the following to register my route.

 

                RouteTable.Routes.Add(new ServiceRoute("route", new HttpServiceHostFactory { Configuration = configuration }, typeof(route)));

Coordinator
Nov 15, 2011 at 5:52 PM

What error do you see on the server?

 
Daniel Roth
Nov 16, 2011 at 8:36 PM

I am running it in VS2010 (Cassini).  No exception is throw and this is what fiddler sees:

HTTP/1.1 504 Fiddler - Receive Failure
Content-Type: text/html; charset=UTF-8
Connection: close
Timestamp: 10:28:35.730

ReadResponse() failed: The server did not return a response for this request.                

 

 

I have tried the different registration, but the response is still the same.  I suspect it is to do with serialization.  The challenge is in the return type.  If I change the following to return MyBlahEntity, then it works.

        [WebGet(UriTemplate = "/Get2/{id}")]
        public BlahEntity Get2(int id)
        {
            return new MyBlahEntity { Id = id, Name = "MyBlah"};    // This doesn't
        }