Create, Deploy and Consume WCF Rest Service
If
you are planning to build, deploy and consume a WCF REST service, below steps
will help you in doing that. In this post I am going to use visual studio 2013
and Framework 4.0.
Let’s
get started
Step
1 – Create a new WCF Service
Step
2 – Define data contract
You
can define the data contract inside the project or you can write them in a
separate class library. In this post I am going to add them in service project.
Class
Name - UserDetails.cs
[DataContract]
public class UserDetails
{
[DataMember]
public int UserSeq { get; set; }
[DataMember]
public string UserId { get; set; }
[DataMember(IsRequired = true)]
public bool IsValidUser { get; set; }
[DataMember]
public string UserName { get; set; }
[DataMember]
public string EmailId { get; set; }
[DataMember]
public string Role { get; set; }
[DataMember]
public string Password { get; set; }
}
Step
2 – Define service methods
You
need to define all your service methods those you want to expose to outside
world under interface class (default IService1.cs).
Class
Name - IUserServices
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "ValudateUser?uID={uID}&pWD={pWD}")]
//[FaultContract(typeof(FaultExceptions))]
UserDetails ValudateUser(string uID, string pWD);
Step
3 –Service method definition
The
service method declaration will be in a separate class and it will achieve by using
the inheritance property of OOPS.
Class
Name – UserDef.cs
public class UserDef : IUserServices
{
///
///
///
///
///
///
public UserDetails ValudateUser(string uID, string pWD)
{
UserDetails ud = new UserDetails();
//write your custom code
return ud;
}
}
Step
4 – Web.config Settings
xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="UserDef">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/WcfServiceLibrary1/UserDef/" />
</baseAddresses>
</host>
<endpoint address="" binding="basicHttpBinding" contract=" IUserServices"></endpoint>
<endpoint address="rest" binding="webHttpBinding" contract=" IUserServices" behaviorConfiguration="MyServiceBehavior" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="MyServiceBehavior">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
Note
– Make sure that contract name is full qualified (Namespace + interface name)
Step
5 – Deployment
- Publish WCF service code.
- Create new website under IIS and make the publish code folder location.
- Make sure that application pool is pointing to framework 4.0
Step
6 – Consume
- HTML Code
<fieldset>
<legend>Login</legend>
<table>
<tr>
<td style="width:50%;font-weight:bold;text-align:right">User Id :</td>
<td style="width:50%"><input type="text" runat="server" id="txtuName" style="width:250px" /></td>
</tr>
<tr>
<td style="width:50%;font-weight:bold;text-align:right">Password :</td>
<td style="width:50%"><input type="password" runat="server" id="txtPassword" style="width:250px" /></td>
</tr>
<tr>
<td colspan="2" style="text-align:center;font-weight:bold">
<asp:Button ID="btnLogin" runat="server" Font-Bold="true" Text="Login" OnClick="btnLogin_Click" />
</td>
</tr>
</table>
</fieldset>
- Code Behind – Using web client.
using (var client = new WebClient())
{
try
{
var userInfo = client.DownloadString(ConfigurationManager.AppSettings["UserServiceURL"].ToString() + "ValudateUser?uID=" + txtuName.Value + "&pWD=" + txtPassword.Value);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UserDetails));
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(userInfo)))
{
var userInfo1 = (UserDetails)serializer.ReadObject(ms);
Session["UserInfo"] = userInfo1;
if (userInfo1.IsValidUser)
Response.Redirect("redirectPage.aspx", true);
}
}
catch (Exception ex)
{
}
}
- Using JqueryJquery Files version
<script src="jquery-1.8.3.js" type="text/javascript"></script>
<script src="jquery-ui.js" type="text/javascript"></script>
Ajax call
$.ajax
({
type: "GET",
url: _SERVICE_URL + 'ValudateUser?uID=' + txtuName.Value + '&pWD=' + txtPassword.Value,
dataType: 'json',
async: true,
cache: false,
success: function (data, status) {
//Add your logic
}
});
Comments