Wednesday, October 19, 2011

Consume WCF REST service in F#

Today I successfully implemented the code for consuming WCF REST service in F#. Funny part here is that, this is my first program in F#.. LOL

Ok.. Here is the code for consuming WCF REST in F#.

module FSModule

#light

open System
open System.Text
open System.Net
open System.IO
open System.Web

// F# uses indenting to define scope. So ensure that you indent properly to get it working
let GetDataFromRest =
     let buffer = Encoding.ASCII.GetBytes("<HelloService_SayHello><input>Hello from F#</input></HelloService_SayHello>") //This is needed if its a POST call
     let req = WebRequest.Create(new Uri("http://localhost/HelloService.svc/SayHello")) :?> HttpWebRequest
     req.Method <- "POST"
     req.ContentType <- "application/xml" //Use accordingly XML or JSON
     req.ContentLength <- int64 buffer.Length
     let reqSt = req.GetRequestStream()
     reqSt.Write(buffer,0,buffer.Length)
     reqSt.Flush()
     req.Close()

     let res = req.GetResponse () :?> HttpWebResponse
     let resSt = res.GetResponseStream()
     let sr = new StreamReader(resSt)
     let x = sr.ReadToEnd()
     sr.Close()
     x.ToString()

Done... To invoke this, you can either use F# or C# or even VB.NET :)

F#

let result = GetDataFromRest()
printfn result

C#

string result = FSModule.GetDataFromRest()