Link to home
Start Free TrialLog in
Avatar of perlwhite
perlwhiteFlag for United States of America

asked on

C# REST PUT

Can someone provide me a very basic example of how to use C# to submit a PUT REST request?
Avatar of Vel Eous
Vel Eous

Create a solution structure as follows:

Solution Root
|- ServiceClient (Console)
    |-- Program.cs
|- ServoceHost (Console)
    |-- App.config
    |-- Program.cs
|- ServiceLibrary (WCF Service Library)
    |-- IHelloWorldService.cs

Open in new window


ServiceLibrary IHelloWorldService.cs
using System.ServiceModel;
using System.ServiceModel.Web;

namespace ServiceLibrary
{
    [ServiceContract]
    public interface IHelloWorldService
    {
        
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/{name}")]
        string SayHello(string name);
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class HelloWorldService : IHelloWorldService
    {
        public string SayHello(string name)
        {
            return string.Format("Hello {0}!", name);
        }
    }
}

Open in new window


ServiceHost Program.cs
using ServiceLibrary;
using System;
using System.ServiceModel.Web;

namespace ServiceHost
{
    class Program
    {
        static void Main(string[] args)
        {
            WebServiceHost host = new WebServiceHost(typeof(HelloWorldService));
            try
            {
                host.Open();
                Console.WriteLine("Press <RETURN> to stop the service");
                Console.ReadLine();
                host.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                host.Abort();
            }
        }
    }
}

Open in new window


ServiceHost App.config
Add the following between the <configuration></configuration> tags in your App.config file.
<system.serviceModel>
  <services>
    <service name="ServiceLibrary.HelloWorldService">
      <host>
        <baseAddresses>
          <add baseAddress="http://localhost:8080/hello"/>
        </baseAddresses>
      </host>
    </service>
  </services>
</system.serviceModel>

Open in new window


ServiceClient Program.cs
using ServiceLibrary;
using System;
using System.ServiceModel.Web;

namespace ServiceClient
{
    class Program
    {
        static void Main(string[] args)
        {
            WebChannelFactory<IHelloWorldService> cf = new WebChannelFactory<IHelloWorldService>(new Uri("http://localhost:8080/hello"));
            IHelloWorldService client = cf.CreateChannel();
            Console.WriteLine("What is your name?");
            string response = client.SayHello(Console.ReadLine());
            Console.WriteLine(response);
            Console.WriteLine("Press <RETURN> to close");
            Console.ReadLine();
        }
    }
}

Open in new window


ServiceHost and ServiceClient both require a reference to the ServiceLibrary project.  Also all projects will require additional references to System.ServiceModel and System.ServiceModel.Web.

You will most likely need to run Visual Studio as an administrator as access to ports is usually restricted, so running this as a non administrator will throw an access denied error in the ServiceHost when attempting to open the port.
Avatar of perlwhite

ASKER

I do not control the service. I have a URL and list of parameters to be passed. All I want to do is insert/update records using PUT/POST. I am able to do GET.
how are you performing GET? Please post your code.
Here is my GET code:

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("//url");
            myRequest.Headers.Add("//key", "//value");
            WebResponse response = myRequest.GetResponse();
            Stream responseData = response.GetResponseStream();

            StreamReader reader = new StreamReader(responseData);

            string responseFromServer = reader.ReadToEnd();
The codeproject article talks about HTTP POST. I am trying to do PUT using REST.
ASKER CERTIFIED SOLUTION
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The API documentation asks me to send some required parameters and they show their sample input in json
ok, creating a JSON string is another topic and deserves another Question.
As a summary, you may need to use the JavaScriptSerializer class. Some tutorial here:
http://blogs.microsoft.co.il/blogs/pini_dayan/archive/2009/03/12/convert-objects-to-json-in-c-using-javascriptserializer.aspx
Once you have your JSON string, use the suggested code with mime type "application/json"