none
Consume WCF Rest Service using C# Client WIndows Form APplication Visual Studio 2013 RRS feed

  • Question

  • Scanerio is,

    I have made a WCF Rest Service  whick is fine as I checked with URL alone. Im trying to consume that Service using CLient C#. Code of IService1.cs is as fellows..

    [WebInvoke(Method = "POST",RequestFormat=WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/addClass")]
            void addClass(ClassData cd);

    code for Service1.svc.cs is as fellow

    public void addClass(ClassData cd)
            {
                AccessEIMS ae = new AccessEIMS();
                DAL.ClassData ecd = new DAL.ClassData();
                ecd.ClassID = cd.ClassID;
                ecd.ClassName = cd.ClassName;
                ecd.Status = cd.Status;
                ae.addClass(ecd);
            }

    Client Code is as fellows

    private void btnSave_Click(object sender, EventArgs e)
            {
                ClassData cd = new ClassData();
                cd.ClassID = Int32.Parse(txtClassID.Text);
                cd.ClassName = txtClassName.Text;
                cd.Status = comboClassStatus.Text;
    
                DataContractJsonSerializer objseria = new DataContractJsonSerializer(typeof(ClassData));
                MemoryStream mem = new MemoryStream();
                objseria.WriteObject(mem, cd);
                try
                {
                    string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
                    WebClient webClient = new WebClient();
                    webClient.Headers["Content-type"] = "application/json";
                    webClient.Encoding = System.Text.Encoding.UTF8;
                    webClient.UploadString("http://localhost:4760/Service1.svc/addClass","POST",data);
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
    }

    Im getting WebException Bad Request 400

    • Moved by Kristin Xie Monday, January 4, 2016 5:22 AM move to appropriate forum
    Friday, January 1, 2016 8:11 AM

Answers

  • You make another classlib project called Entities where you have the datacontract class. Then all projects client and service  set project reference to the Entities project. You only need one class using one namespace.  The class name should be prefixed or suffixed with DTO, because that is what it is a DTO.

    https://en.wikipedia.org/wiki/Data_transfer_object

    Friday, January 1, 2016 3:01 PM
  • is this standard way? independency between Service and client  will be still exists?

    It is just an object, a data transfer object,  being passed between two processes the client process and the service process. The design pattern is used in the real world all the time so just use it and be done with it. 
    Friday, January 1, 2016 3:18 PM

All replies

  • You posted this in the WCF forum. You can be told no more here in the C# forum that has been  told to you in the WCF forum.

    You have been told what the 400 means, which is a general error thrown by the Web server. It in no way reflects the actual/true/real exception that  your Web service through. You need to do what has been told to you to find out what exception your program through.

    You are not coming around it, there is no one that has the magic bullet and you are the one that has to dig out the true/actual exception that was thrown by your program, which you were given ways on how to do it.

    Friday, January 1, 2016 12:06 PM
  • ok tell me one thing. DataContract Class which I made in  Rest Service project

    namespace EIMSServices
    {
        [DataContract]
        public class ClassData
        {
            [DataMember]
            public int ClassID { get; set; }
    
            [DataMember]
            public string ClassName { get; set; }
    
            [DataMember]
            public string Status { get; set; }
        }
    }

    i also made same class in UI project  code of that class is below

    namespace EIMS
    {
        public class ClassData
        {
    
            public int ClassID { get; set; }
    
    
            public string ClassName { get; set; }
    
    
            public string Status { get; set; }
    
        }
    }

     im passing object of this class (UI.DataClass) in URL . but method on Service side expecting Object of type (EIMSService.ClassData). I suspect this , is it fine method? or I have to use .dll of DataContract class on UI Side?

    look at my projects in  pic

    Friday, January 1, 2016 2:07 PM
  • You make another classlib project called Entities where you have the datacontract class. Then all projects client and service  set project reference to the Entities project. You only need one class using one namespace.  The class name should be prefixed or suffixed with DTO, because that is what it is a DTO.

    https://en.wikipedia.org/wiki/Data_transfer_object

    Friday, January 1, 2016 3:01 PM
  • is this standard way? independency between Service and client  will be still exists?
    Friday, January 1, 2016 3:11 PM
  • is this standard way? independency between Service and client  will be still exists?

    It is just an object, a data transfer object,  being passed between two processes the client process and the service process. The design pattern is used in the real world all the time so just use it and be done with it. 
    Friday, January 1, 2016 3:18 PM
  • Hi Zaid Mirza,

    I create a test project with Restful Service and consume it with WinForm. It works fine.

    My client code:

    private void PassObject_Click(object sender, EventArgs e)
            {
    
                WebClient WC = new WebClient();
                WC.Headers["Content-type"] = "application/json";
    
                CompositeType CT = new CompositeType();
                CT.BoolValue = true;
                CT.StringValue = txtMyName.Text;
    
                MemoryStream MS = new MemoryStream();
                DataContractJsonSerializer JSrz = new DataContractJsonSerializer(typeof(CompositeType));
    
                JSrz.WriteObject(MS, CT);
    
                byte[] res1 = WC.UploadData(ServiceUrl + "PostCompositeType", "POST", MS.ToArray());
    
                Stream res2 = new MemoryStream(res1);
                JSrz = new DataContractJsonSerializer(typeof(CompositeType));
    
                CT = (CompositeType)JSrz.ReadObject(res2);
    
                Console.WriteLine(CT.StringValue);
    
            }

    My server code:

    [OperationContract]
            [WebInvoke(Method = "POST", UriTemplate = "/PostCompositeType", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
            CompositeType GetDataUsingDataContract(CompositeType composite);

    Result:

    If you want to store the data to database, you can use the entity framework to processes the

    data.

    For more information, please refer to the following articles:

    1.http://www.developerhandbook.com/wcf/restful-web-service-using-wcf-1-of-3/

    2.http://www.developerhandbook.com/wcf/how-to-create-a-restful-web-service-using-wcf-part-2-of-3/

    3.http://www.developerhandbook.com/wcf/how-to-create-a-restful-web-service-using-wcf-part-3-of-3/

    =============================================================

    This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.

    Best Regards,

    Wanjun Dong


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. Click HERE to participate the survey.

    Tuesday, January 19, 2016 10:53 AM
    Moderator