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:
I call my service AzureRestullServiceSample
2. Add one WCFServiceWebRole:
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:
[DataContract]
public class UserData
{
private long m_UserID;
private string m_UserName;
private string m_UserPassword;
private string m_UserCell;
private string m_UserMail;
[DataMember]
public long UserID
{
get { return m_UserID; }
set { m_UserID = value; }
}
[DataMember]
public string UserName
{
get { return m_UserName; }
set { m_UserName = value; }
}
[DataMember]
public string UserPassword
{
get { return m_UserPassword; }
set { m_UserPassword = value; }
}
[DataMember]
public string UserCell
{
get { return m_UserCell; }
set { m_UserCell = value; }
}
[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:
[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:
- 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
- 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:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
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:
- In file SampleService.svc open markup and make sure that Service property points to your class in my case this is : Service="WCFServiceWebRole.SampleService"
- 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):
<span style="font-family: Calibri; font-size: 11pt;"></span>="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">
<serviceMetadata httpGetEnabled="true"/>
<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>
</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:
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.
Let's run request and see what we received:
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.