C# REST PUT

Can someone provide me a very basic example of how to use C# to submit a PUT REST request?
perlwhiteAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Vel EousResearch & Development ManagerCommented:
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.
perlwhiteAuthor Commented:
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.
Jaime OlivaresSoftware ArchitectCommented:
how are you performing GET? Please post your code.
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Rose BabuSenior Team ManagerCommented:
perlwhiteAuthor Commented:
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();
perlwhiteAuthor Commented:
The codeproject article talks about HTTP POST. I am trying to do PUT using REST.
Jaime OlivaresSoftware ArchitectCommented:
What are you trying to put? a string or xml?
For a plain text it would be something like:

// Prepare data to send
string str = "this is the information to send"; 
byte[] data = new System.Text.UTF8Encoding().GetBytes(str); 

// Prepare request headers
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url"); 
request.Method = "PUT"; 
request.ContentType = "text/plain"; 
request.ContentLength = data.Length; 
request.KeepAlive = true; 

// Stream data
dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length); 
dataStream.Close(); 

// Get the response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
perlwhiteAuthor Commented:
The API documentation asks me to send some required parameters and they show their sample input in json
Jaime OlivaresSoftware ArchitectCommented:
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"
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
WCF

From novice to tech pro — start learning today.