Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Posting data to a REST service using C#

As Rest services are becoming more and more common the need is arising to be able to post data to them via .net.  Now normally when you want to post data to a web resource you normally would do so using a web service.  And when you use a web service all the ‘plumbing’ is taking care of for you by the .Net framework.  However since we are not posting to a web service there is a bit of code you need to create in order to post to a REST service.  The good news is that the amount of code you need to create is not all the bad.

Lets pretend we want to post data to the following REST service http://localhost:2844/Home/PostDataTester which takes in 3 values

  1. someValue which is a string
  2. anotherValue which is a string
  3. finalValue which is an Int32

Now that we know what the REST service contract looks like we should take a look at the code needed to actually connect to and post the data.

First we are going to look at the main logic which will post the data, however, this method has 2 helper methods which we also need to discuss.

public void SendMessage( string endPoint, Dictionary< string, string > paramters)
{
    var populatedEndPoint = CreateFormattedPostRequest( paramters );
    byte[] bytes = Encoding.UTF8.GetBytes( populatedEndPoint );

    HttpWebRequest request = CreateWebRequest( endPoint, bytes.Length );

    using ( var requestStream = request.GetRequestStream() )
    {
        requestStream.Write( bytes, 0, bytes.Length );
    }

    using ( var response = (HttpWebResponse)request.GetResponse() )
    {
        if ( response.StatusCode != HttpStatusCode.OK )
        {
            string message = String.Format( "POST failed. Received HTTP {0}", response.StatusCode );
            throw new ApplicationException( message );
        }
    }
}

As you can see from above, the code needed to actually post the data is not too bad, in fact it is fairly simple.  Now that we have seen the main logic lets take a look at the various helpers methods.

The first helper method is the method which will actually create the HttpWebRequest object for us

private HttpWebRequest CreateWebRequest( string endPoint, Int32 contentLength )
{
    var request = (HttpWebRequest)WebRequest.Create( endPoint );

    request.Method = "POST";
    request.ContentLength = contentLength;
    request.ContentType = "application/x-www-form-urlencoded";

    return request;
}

Pay close attention to 2 things here

  1. The method on the request must be POST
  2. The content type on the request must be application/x-www-form-urlencoded

The second helper method will take in a list of values which need to be posted and create the value query string for posting

private string CreateFormattedPostRequest( ICollection> values )
{
    var paramterBuilder = new StringBuilder();
    var counter = 0;
    foreach ( var value in values )
    {
        paramterBuilder.AppendFormat( "{0}={1}", value.Key, HttpUtility.UrlEncode( value.Value ) );

        if ( counter != values.Count - 1 )
        {
            paramterBuilder.Append( "&" );
        }

        counter++;
    }

    return paramterBuilder.ToString();
}

Pay close attention to the fact that we are doing UrlEnoding on our values which we are pushing to the service, this is very, very important.

As you can see, the actual code to post a message to a REST service is simple and trivial and can be implemented with very little effort.

Till next time,


Posted 02-14-2009 3:23 AM by Derik Whittaker
Filed under: ,

[Advertisement]

Comments

DotNetKicks.com wrote Posting data to a REST service using C#
on 02-14-2009 4:24 AM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetShoutout wrote Posting data to a REST service using C#
on 02-14-2009 4:56 PM

Thank you for submitting this cool story - Trackback from DotNetShoutout

Derik Whittaker wrote Getting data from a REST service using C#
on 02-15-2009 3:32 AM

As REST services are becoming more and more common the need is arising to be able to retrieve data to

Community Blogs wrote Getting data from a REST service using C#
on 02-15-2009 3:59 AM

As REST services are becoming more and more common the need is arising to be able to retrieve data to

Reflective Perspective - Chris Alcock » The Morning Brew #287 wrote Reflective Perspective - Chris Alcock &raquo; The Morning Brew #287
on 02-16-2009 3:37 AM

Pingback from  Reflective Perspective - Chris Alcock  &raquo; The Morning Brew #287

ASP.NET wrote Posting data to a REST service using C# - Derik Whittaker
on 02-17-2009 12:32 PM

Posting data to a REST service using C# - Derik Whittaker

vietnamese developer wrote re: Posting data to a REST service using C#
on 02-18-2009 4:28 AM

Thanks alot !!!

Anonymou wrote re: Posting data to a REST service using C#
on 03-08-2009 6:35 PM

Yea, I love the "very little effort".  That is...if you're already very familiar with it.

Anonymous wrote re: Posting data to a REST service using C#
on 03-08-2009 7:07 PM

would have been more helpful if we could have seen what the actual request url looks like and params in context to what you're working with.

Anonymous wrote re: Posting data to a REST service using C#
on 03-08-2009 7:08 PM

Is this all held in one class?  What's your class structure for this including member fields?

Anonymous wrote re: Posting data to a REST service using C#
on 03-08-2009 8:12 PM

what's the value of "endpoint" ?

Anonymous wrote re: Posting data to a REST service using C#
on 03-09-2009 12:19 AM

What if you wanted to perform a GET...which I believe doesn't send xml but just method and params.   Does your code account for that?

Yuri wrote re: Posting data to a REST service using C#
on 05-26-2009 4:01 PM

very helpful. Thank you

Yuri wrote re: Posting data to a REST service using C#
on 05-26-2009 4:03 PM

Very helpful. Thank you

fg wrote re: Posting data to a REST service using C#
on 05-26-2009 4:04 PM

what about vb.net???

James H wrote re: Posting data to a REST service using C#
on 05-26-2009 4:04 PM

What about VB.NET???

Lightning Tools Blog wrote Using Twilio with SharePoint to send SMS messages
on 02-03-2012 5:04 AM

Using Twilio with SharePoint to send SMS messages

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)