Wednesday, July 11, 2012

Consuming a WCF REST Service in ASP.NET

REST (Representational State Transfer) services are quickly becoming the de-facto standard for web services in SOA (Solution Oriented Architecture) architectures.  This example demonstrates how to consume a REST service in WCF (Windows Communication Foundation) with Visual Studio 2010 with support for JSON (Javascript Object Notation) and XML formats.
This project, with complete source code is available for download at https://bitbucket.org/barkes/presidentsweb.


The PresidentsService project (required for this demo) is available for download at https://bitbucket.org/barkes/presidentsservice.

To Consume a WCF REST Service in ASP.NET

  1. Create a new project in Visual Studio named PresidentsWeb by selecting the ASP.NET Web Application project template in the Web category.

  2. Add a reference to our presidents WCF service by right-clicking the project in the Solutions Explorer and clicking the Add Service Reference menu.  On the Add Service Reference dialog enter the URI of the WCF service in the Address textbox.  In this example, we're using the custom Presidents WCF REST Service hosted locally at http://localhost:9140/PresidentsService.svc.  Click the Go button.  Enter PresidentsService as the Namespace and click the OK button.


  3. Add a new WFC Service named PresidentsService.svc.  Right-click your project, click Add.  Then click New Item.  Select the WCF Service item from the Web category in the Add New Item dialog.


  4. Open Default.aspx and add the following table - please note this has been shortened for readability purposes, but the source download contains the complete listing.
     Default.aspx
    <table cellpadding="5px">
        <tr><td>
            <asp:Label ID="ServiceUrlLabel" runat="server" Text="Service URL:">
            <⁄asp:Label>
        <⁄td><td class="style1">
            <asp:TextBox ID="ServiceUrlTextBox" runat="server" Width="600px">
            <⁄asp:TextBox>
        <⁄td>tr>
     
        <tr valign="top"><td>
            <asp:Label ID="ResultLabel" runat="server" Text="Results:">
            <⁄asp:Label>
        <⁄td><td class="style1">    
                <asp:TextBox ID="ResultsTextBox" runat="server" Width="600px" 
                    Height="200px" ReadOnly="True" TextMode="MultiLine">
                <⁄asp:TextBox>
        <⁄td><⁄tr>
     
        <tr><td>
             
        <⁄td><td class="style1">    
            <asp:Button ID="GetResultsButton" runat="server" 
                onclick="GetResultsButton_Click" 
                Text="Get Results" />
        <⁄td><⁄tr>
    <⁄table>
    
  5. Open Default.aspx.cs from the Solution Explorer and add the implementation for the GetResultsButton_Click event handler.  In this method, the .NET class WebClient is used to send and receive data from the URI resource and the DataContractJsonSerializer to de-serialize the data.
     Default.aspx.cs
    protected void GetResultsButton_Click(object sender, EventArgs e)
    {
        string url = ServiceUrlTextBox.Text;
             
        WebClient client = new WebClient();
        byte[] data = client.DownloadData(new Uri(url));
        Stream stream = new MemoryStream(data);
        StreamReader reader = new StreamReader(stream);
                
        DataContractSerializer dcs = 
            new DataContractSerializer(typeof(string));
        DataContractJsonSerializer jcs = 
            new DataContractJsonSerializer(typeof(PresidentsService.President));
     
        PresidentsService.President president = 
            (PresidentsService.President) jcs.ReadObject(stream);
     
        string result = 
            string.Format("~~ De-serialized JSON Object (DataContractJsonSerializer)\n{0} {1} ({2})",
            president.FirstName, president.LastName, president.EmailAddress);
     
        stream.Position = 0;
        result = 
            result + "\n\n~~ Raw JSON Data (StreamReader)\n" + reader.ReadToEnd();
     
        ResultsTextBox.Text = result;
    }
    

Test the ASP.NET Application

  1. Since this application utilizes the Presidents WCF REST Service, make sure the service is running before you execute the PresidentsWeb application.  In Visual Studio, select the Debug menu, then Start Debugging.  Alternately, the debugger may be launched using the F5 key.  In the Service URL, enter the REST URI, then click the Get Results button.



1 comment:

  1. Everything in this article was SOOOO easy and great and worked perfectly just by following your steps. However you forgot to show the steps of adding the datacontract, and step 3 is not needed.

    Other than that. MUCH Appreciated! Thank You!

    ReplyDelete