简体   繁体   中英

wcf rest json return collection

I am attempting to build a Restful WCF Service which returns data in JSON format. My firsts methods work fine but when I try return a collection my test program receive the next exception:

Unable to write data to the transport connection. An existing connection was forcibly closed by the remote host.

My Service code:

[ServiceContract]
public interface IService
{ 
  [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/GetModes")]
    OGetModesResponse OGetModes(OGetModesRequest oGetModes);
}
[DataContract]
public class OGetModesRequest
{
    private String m_sTicket;

    [DataMember]
    public String prTicket
    {
        get { return m_sTicket; }
        set { m_sTicket = value; }
    }
}

[DataContract]
public class OGetModesResponse
{
    [DataMember]
    public string sTicket;
    [DataMember]
    public emStatus emStatus;
    [DataMember]
    public IList<CTMode> aoModes;
}

And my test program:

OGetModesRequest oGetModes = new OGetModesRequest { prTicket = sTicket };
ser = new DataContractJsonSerializer(typeof(OGetModesRequest));
mem = new MemoryStream();
ser.WriteObject(mem, oGetModes);
webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
//Exception here
bData = webClient.UploadData("http://localhost:26104/Service.svc/GetModes", "POST", mem.ToArray()); 
stream = new MemoryStream(bData);
obj = new DataContractJsonSerializer(typeof(OGetModesResponse));
OGetModesResponse OResultModes = obj.ReadObject(stream) as OGetModesResponse;

I debug my services and works fine. What can be happening?

Thanks for help.

Edit (solution): CTMode is a class used by managing object that I obtain using NHibernate so I create a new class serializable called CMode

[DataContract]
public class OGetModesResponse
{
    [DataMember]
    public string sTicket;
    [DataMember]
    public emStatus emStatus;
    [DataMember]
    public IList<CMode> aoModes;
}
[Serializable]
public class CMode
{
    public Int32 nId;
    public Int32 nCode;
    public String sName;
}

Try to check inner exception and add some logging/ trace on the server.

There are few possibilities for your (generic) error as you may not be aware about inner exception:

  • object CTMode is missing DataContract, DataMember attribute.
  • object CTMode is an enum that missing attributes or has incorrect value that cannot be serialized
  • previous connection is not closed correctly
  • there is a proxy server on the way and you need to bypassed it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM