Search code examples
jsonwcf

How to post json data to wcf service


how to post call SaveCorporateProfile function by passing json

[DataContract]
public class myclass
{
    public string CompanyCode { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}



 [ServiceContract]
    public interface ICustProfileService
    {
        [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/SaveCorporateProfile?dt={dt}")]
        string SaveCorporateProfile(myclass dt);
    }

public string SaveCorporateProfile(myclass dt)
        {          

            return "success";
        }

Solution

  • You can try this;

    Firstly, you should edit your myclass like this;

    [DataContract]
    public class myclass
    {
    
        [DataMember]
        public string CompanyCode { get; set; }
    
        [DataMember]
        public string Username { get; set; }
    
        [DataMember]
        public string Password { get; set; }
    }
    

    then your interface like this;

     [ServiceContract]
    public interface ICustProfileService
    {
        [OperationContract]
        string SaveCorporateProfile(myclass dt);
    }
    

    And you implement your .svc file for using this interface

     public class CustProfileService: ICustProfileService
    {
      [WebInvoke(Method = "POST",UriTemplate = "/SaveCorporateProfile?dt={dt}"
       BodyStyle = WebMessageBodyStyle.Bare,
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json)]
    
        public string SaveCorporateProfile(myclass dt)
        {          
    
            return "success";
        }
    
    }