C# – why the WCF client gets empty result

cnetvisual-studio-2008wcf

I am using VSTS 2008 + .Net + C# 3.5 to develop WCF service (self-hosted as a Windows Service). From client side, I am using ChannelFactory to connect to WCF service. My confusion is, when I change client side code from "public string response" to "public string responseAliasName", the value of responseAliasName is null. But when change back to variable name response, the response value is correct (value is "hi WCF").

My confusion is, I think variable name should not matter as long as the layout is the same from client and server side. Any ideas what is wrong?

Server side code:

namespace Foo
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
    [ServiceContract]
    public interface IFoo
    {
        [OperationContract]
        FooResponse Submit(string request);
    }

    [DataContract]
    public class FooResponse
    {
        [DataMember]
        public string response;
    }
}

namespace Foo
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
    public class FooImpl : IFoo
    {
        public FooResponse Submit(string request)
        {
            FooResponse foo = new FooResponse();
            foo.response = "hi WCF";
            return foo;
        }
    }
}

Client side code:

namespace Foo
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
    [ServiceContract]
    public interface IFoo
    {
        [OperationContract]
        FooResponse Submit(string request);
    }

    [DataContract]
    public class FooResponse
    {
        [DataMember]
        // public string responseAliasName;
        public string response;
    }
}


namespace FooTestClient1
{
    class Program
    {
        static void Main(string[] args)
        {
            ChannelFactory<IFoo> factory = new ChannelFactory<IFoo>(
               "IFoo");
            IFoo f = factory.CreateChannel();
            FooResponse response = f.Submit("Hi!");

            return;
        }
    }
}

Best Answer

you can use

[DataContract(Name="ResponseAliasName")]
public string response;

on Server side and it will work as you expect, DataContract by default uses field or property name to serialize data, and the server can't find correct data

Related Topic