none
How to consume REST API in c# RRS feed

  • Question

  • Hi Everybody,

    I have created WCF REST service using c#, How its client consume the REST service?

    Thanks in advance.

    Tuesday, January 5, 2016 12:07 PM

Answers

All replies

  • Hi Everybody,

    I have created WCF REST service using c#, How its client consume the REST service?

    Thanks in advance.


    Did you search the form topics first as there is a thread not 5 threads away from your post that is covering the topic. 
    Tuesday, January 5, 2016 1:43 PM
  • Hi Sunil404,

    Here is some helpful documentation from MSDN: https://msdn.microsoft.com/en-us/library/bb386386.aspx

    In a nutshell, you will right click your project within the solution and choose "Add Service Reference".  You copy the path to the .svc file into the address box and click "Discover", from there it should connect to your WCF service and allow you to create a service reference to your WCF service.  You can then work with classes and methods exposed by your service.

    Best of luck.


    • Edited by DPCodesalot Tuesday, January 5, 2016 2:00 PM
    Tuesday, January 5, 2016 1:59 PM
  • I suggest you to refer these below MSDN forum threads:

    Consume API Restful Service with C#
    How create and Consume Post methode Rest Wcf Service
    Consume Rest Wcf Service in Client side in asp.net C#

    Go through this step by step tutorial to understand it better..
    Building and Testing WCF RESTful services

    MSDN documentation - Consuming WCF Services

    Create a client app and add a Service Reference.

     

    -Niranjan Kala http://www.niranjankala.in

    Tuesday, January 5, 2016 2:04 PM
  • Hi Niranjan Kala,

    As far as I know, we can use the  httpwebrequest and httpwebresponse or webclient classes

    in our client to call our service.

    Here is my sample:

    Service code:

    [OperationContract]            
            [WebInvoke(Method = "PUT", UriTemplate = "/PutString",
              RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
            string PutString(string value);
    
            [OperationContract]
            [WebGet(UriTemplate = "GetSampleMethod/inputStr/{name}",ResponseFormat=WebMessageFormat.Json)]
            string GetSampleMethod(string name);

    Method:

     public string PutString(string value)
            {
                return value += "..PutString get called";
            }
    
              public string GetSampleMethod(string strUserName)
            {
                StringBuilder strReturnValue = new StringBuilder();
                // return username prefixed as shown below
                strReturnValue.Append(string.Format
    		    ("You have entered userName as {0}", strUserName));
                return strReturnValue.ToString();
            }

    Client Code:

      static void PutMethod()
            {
                string ServiceUrl;
                ServiceUrl = @"http://LocalHost:7789/MySericeDemo/";
                WebClient WC = new WebClient();
                WC.Headers["Content-type"] = "application/xml";
    
                MemoryStream MS = new MemoryStream();
                DataContractSerializer JSrz = new DataContractSerializer(typeof(string));
                string NAME = "ABC";
                JSrz.WriteObject(MS, NAME);
                byte[] res1 = WC.UploadData(ServiceUrl + "PutString", "PUT", MS.ToArray());
    
                MS = new MemoryStream(res1);
                JSrz = new DataContractSerializer(typeof(string));
                string result = (string)JSrz.ReadObject(MS);
    
                Console.WriteLine(result);
            }
            static void CallGetMethod()
            {           
                string url = "http://LocalHost:7789/MySericeDemo/GetSampleMethod/inputStr/suryaprakash";
                string strResult = string.Empty;
                HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
                webrequest.Method = "GET";
                webrequest.ContentType = "application/json";
                HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
                Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
                StreamReader loResponseStream = new StreamReader
    				(webresponse.GetResponseStream(), enc);
                strResult = loResponseStream.ReadToEnd();
                loResponseStream.Close();
                webresponse.Close();
                Console.WriteLine(strResult);
            }

    Result:

    Hope it helps.

    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.

    Sunday, January 24, 2016 6:28 AM
    Moderator
  • WCF and REST are different things. For a WCF service, you should generate a Service Reference.

    For a REST service aka. Web API, you can use a Rest Client like RestClient.Net.

    Some samples:

    Get

    With Newtonsoft serialization

    varclient=newClient(newNewtonsoftSerializationAdapter(), newUri("https://restcountries.eu/rest/v2/"));
    varresponse=awaitclient.GetAsync<List<RestCountry>>();

    With default serialization on .NET Core

    var client = new Client(new Uri("https://restcountries.eu/rest/v2/"));
    var response = await client.GetAsync<List<RestCountry>>();

    Protocol Buffers (Binary)

    var person = new Person { FirstName = "Bob", Surname = "Smith" };
    var client = new Client(new ProtobufSerializationAdapter(), new Uri("http://localhost:42908/person"));
    person = await client.PostAsync<Person, Person>(person);

    JSON

    var client = new Client(new NewtonsoftSerializationAdapter(), new Uri("https://jsonplaceholder.typicode.com"));
    client.SetJsonContentTypeHeader();
    UserPost userPost = await client.PostAsync<UserPost, UserPost>(new UserPost { title = "Title" }, "/posts");

    Delete

    varclient=newClient(newNewtonsoftSerializationAdapter(), newUri("https://jsonplaceholder.typicode.com"));
    awaitclient.DeleteAsync("posts/1");







    Thursday, January 23, 2020 9:10 AM