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 { getset; }
 
    [DataMember]
    public string UserId { getset; }
 
    [DataMember(IsRequired = true)]
    public bool IsValidUser { getset; }
 
    [DataMember]
    public string UserName { getset; }
 
    [DataMember]
    public string EmailId { getset; }
 
    [DataMember]
    public string Role { getset; }
 
    [DataMember]
    public string Password { getset; }
}


 


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


  1. Publish WCF service code.
  2. Create new website under IIS and make the publish code folder location.
  3. Make sure that application pool is pointing to framework 4.0


Step 6 – Consume


  1. 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>


 


  1. 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)
     {
     }
 }


 


  1. Using Jquery
    Jquery 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

Popular posts from this blog

SSIS Merge Join - Both inputs of the transformation must contain at least one sorted column, and those columns must have matching metadata SSIS

jsGrid

Add Item to SharePoint List with attachment using client object model