Search code examples
.netwcfwcf-data-services

Need help in controlling data contract wcf


I am working on WCF and want to control the output of my service. Here are my classes:

[DataContract]
public class Authenticate
{
[DataMember(order=1)]
public int result;
[DataMember(order=0)]
Public string message;
}

[Operation Contract]
public interface IService1
{
Authenticate Login(string UName,string Password);
}

public class Service1:IService1
{
public Authenticate Login(string UName,string Password)
{
Authenticate result=new Authenticate();
if(UName=="mohit" && Password=="mohit")
{
result.result=1;
result.message="success";
}
else
{
result.result=0;
result.message="failure";

}
return result;
}
}

The Output XML of this method(Ignoring Metadata tags) is

<LoginResponse>
<LoginRsult>
<a:message>success</a:message>
<a:result>1</a:result>
</LoginRsult>
</LoginResponse>

What i want as output is:

<authenticate>
<result>1</result>
<message>success</message>
</authenticate>

I tried setting the name in Datamember that did not work.

Also whatever I set the order in the datamember the message tag always appears before result (seems like in alphabetic order).


Solution

  • In your example you are explicitly setting the order of the DataMembers:

    [DataContract]
    public class Authenticate
    {
        [DataMember(order=1)]
        public int result;
        [DataMember(order=0)]
        Public string message;
    }
    

    It goes in order from lowest to highest, so you have specifically defined the order of the output to be the way it is actually happening. If you want result to go first, and message second reverse the values of order:

    [DataContract]
    public class Authenticate
    {
        [DataMember(order=0)]
        public int result;
        [DataMember(order=1)]
        Public string message;
    }