Click here to Skip to main content
15,867,704 members
Articles / Programming Languages / C# 5.0

Azure WCF RESTULL Service with HTTP GET and POST methods sample tested by Postman

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
20 Apr 2015CPOL3 min read 12K   114  
This is a sample article that describes ho to implement RESTfull service for Azure for both GET and POST methods

Introduction

Here I'm going to show you my POC project that I've done to understand how Azure Web Service that exposes RESTfull WCF contract can be used for both GET and POST methods.

Steps done

1.  Run visual studio and create new Azure Cloud service:

Image 1

I call my service AzureRestullServiceSample

2.  Add one WCFServiceWebRole:

Image 2

3. I renamed interface file and service implementation to ISampleService.cs and SampleService.svc accordingly

4.  Let's think our interface is for user management system. We plan to have here methods to add and read users using HTTP methods. For this purpose we need to define class UserData:

C#
[DataContract]
public class UserData
{
    private long   m_UserID;       //ID of the user
    private string m_UserName;     //name of the user
    private string m_UserPassword; //user's password
    private string m_UserCell;     //user's cell phone number
    private string m_UserMail;     //user's mail

    /// <summary>
    /// ID of the user
    /// </summary>
    [DataMember]
    public long UserID
    {
        get { return m_UserID; }
        set { m_UserID = value; }
    }
    /// <summary>
    /// name of the user
    /// </summary>
    [DataMember]
    public string UserName
    {
        get { return m_UserName; }
        set { m_UserName = value; }
    }
    /// <summary>
    /// user's password
    /// </summary>
    [DataMember]
    public string UserPassword
    {
        get { return m_UserPassword; }
        set { m_UserPassword = value; }
    }
    /// <summary>
    /// user's cell phone number
    /// </summary>
    [DataMember]
    public string UserCell
    {
        get { return m_UserCell; }
        set { m_UserCell = value; }
    }
    /// <summary>
    /// user's mail
    /// </summary>
    [DataMember]
    public string UserMail
    {
        get { return m_UserMail; }
        set { m_UserMail = value; }
    }
}

5. Now we are going to define methods to read users and add new user\s to the system:

C#
[ServiceContract]
public interface ISampleService
{
    [OperationContract]
    [WebInvoke( UriTemplate = "getusers",
                Method = "GET",
                RequestFormat = WebMessageFormat.Json,
                ResponseFormat = WebMessageFormat.Json,
                BodyStyle = WebMessageBodyStyle.Wrapped)]
    bool GetAllUsers(out List<UserData> users);

    [OperationContract]
    [WebInvoke(UriTemplate = "adduser",
                Method = "POST",
                RequestFormat = WebMessageFormat.Json,
                ResponseFormat = WebMessageFormat.Json,
                BodyStyle = WebMessageBodyStyle.Wrapped)]
    bool AddUser(List<UserData> users);
}

Here I want to explain a little bit. We use set of attributes here that require explanation:

  1. OperationContract attribute makes defined method exposable in Service Contract. If you don't use this attribute method will not be accessible from outside. https://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontractattribute(v=vs.110).aspx
  2. WebInvoke attribute indicates that operation may be called by WCF REST programming model https://msdn.microsoft.com/en-us/library/system.servicemodel.web.webinvokeattribute(v=vs.110).aspx Once we use Method="GET" to indicate GET HTTP method and once we use "POST" to identify POST call. We also user Json as request and response format for our HTTP method

​6. Let's implement both GET and POST methods:

C#
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] //without this attribute service doesn't work this is service added manually to project
public class SampleService : ISampleService
{
    public bool GetAllUsers(out List<UserData> users)
    {

        users = new List<UserData>();
        for (int i = 0; i < 3; i++)
        {
            UserData user = new UserData();
            user.UserID = i;
            user.UserCell = "1111" + i.ToString();
            user.UserMail = "TestMail" + i.ToString();
            user.UserName = "UserName" + i.ToString();
            user.UserPassword = "UserPassword" + i.ToString();
            users.Add(user);
        }
        return true;
    }

    public bool AddUser(List<UserData> users)
    {
        return true;
    }
}

7. Now we can run our service and test both methods. But before you need to make sure about few things:

  1. In file SampleService.svc open markup and make sure that Service property points to your class in my case this is :  Service="WCFServiceWebRole.SampleService"
  2. In WebConfig file you must have your service with binding "webHttpBinding". Most critical parts of my webconfig files are below  (full version of WebConfig file you can open in attached project sources):
XML
<span style="font-family: Calibri; font-size: 11pt;"></span><?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="ServiceBahavior" name="WCFServiceWebRole.SampleService">
        <endpoint behaviorConfiguration="MyServiceBehavior" binding="webHttpBinding"
          bindingConfiguration="MyBindingConfiguration" name="serviceConfiguration"
          contract="WCFServiceWebRole.ISampleService" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="MyServiceBehavior">
          <webHttp helpEnabled="true" automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Xml" />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="ServiceBahavior">
          <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="MyBindingConfiguration" allowCookies="true" sendTimeout="00:01:00" bypassProxyOnLocal="false"
         hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647"
         maxBufferPoolSize="52428800" maxReceivedMessageSize="2147483647" transferMode="Buffered" useDefaultWebProxy="true">
          <security mode="None" />
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647"
            maxBytesPerRead="20000" maxNameTableCharCount="16384" ></readerQuotas>
          <!--security mode="Transport" /-->
        </binding>
      </webHttpBinding>
    </bindings>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
</configuration>

8. Let's test GET method. I'm running service in GoogleChrom and request for add users URL. As result I receive all users that I generate with their details:

Image 3

The perfect thing here is that you shouldn't care about serializing your output data structure to JSON. WCF does it for you, all you need is to enjoy using your API via HTTP. I'm not sure about very complex types with binary data, probably you need to add some serialization, but usual classes with primitive data types are serialized perfectly.

9. Now let's test POST method. For this purpose I added Postman tool to my Chrome browser. This tool gives you ability to send POST requests to service. I used following link to get familiar with using GET and POST calls from Postman: http://docs.brightcove.com/en/video-cloud/player-management/guides/postman.html

Below is my screen with data that I've entered to postman to do POST request and path to it list from 3 users, where last user has not all fields (I did this for debug purposes and to check that WCF will map everything properly). I spent about 1 hour to build proper JSON here, my mistake was that I didn't use parameter name: "users". If I don’t use it, HTTP POST call doesn't parse input JSON and my input parameter to function was equal to null.

Image 4

Let's run request and see what we received:

Image 5

I specially show to you first element where I fill all data and last where we didn't pass some parameters and they are equal to null.


 

That's all, now you can extend this service with any numbers of GET and POST methods and enjoy your staying with WCF and Azure. Sources of the sample project are attached to this article you can download and run them on your system.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Ukraine Ukraine
Working on different projects and technologies from web to low level core programming, from scripting languages to C++. With all this stuff my personal opinion is that C#,.NET and Microsoft environment is the best thing programmer may have. Basing on it I prefer to publish only about my favorite technologies that are .NET and Azure now.

P.S. Looking for partnership and cooperation in outsourcing.

Comments and Discussions

 
-- There are no messages in this forum --