Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

C# REST PUT

Posted on 2012-09-08
9
Medium Priority
?
1,897 Views
Last Modified: 2012-09-09
Can someone provide me a very basic example of how to use C# to submit a PUT REST request?
0
Comment
Question by:perlwhite
9 Comments
 
LVL 14

Expert Comment

by:Vel Eous
ID: 38380109
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.
0
 

Author Comment

by:perlwhite
ID: 38380229
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.
0
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 38380304
how are you performing GET? Please post your code.
0
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

 
LVL 16

Expert Comment

by:Rose Babu
ID: 38380513
0
 

Author Comment

by:perlwhite
ID: 38380792
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();
0
 

Author Comment

by:perlwhite
ID: 38380793
The codeproject article talks about HTTP POST. I am trying to do PUT using REST.
0
 
LVL 55

Accepted Solution

by:
Jaime Olivares earned 1500 total points
ID: 38380815
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

0
 

Author Comment

by:perlwhite
ID: 38381353
The API documentation asks me to send some required parameters and they show their sample input in json
0
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 38381464
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"
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses
Course of the Month20 days, 19 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question