Create WCF RESTful Service With IIS Hosting And Consuming

Today I am sharing how to create restful api HOSTing and consuming in IIS  ... it's really interesting to create and use services. This article is divided into two parts. the first part describes how to create services, design architecture, binding configuration,  and hosting in IIS, and the second part describes how to consume this service in different applications like windows application, web application, and mobile application.

INTRODUCATION

This document describes how to create REST API, which allows users to achieve most tasks that can be done from the web UI programmatically. The API accepts JSON content as input. The output is always in JSON or xml (or empty, in the case of DELETE requests.

Let’s start the first one

  1. Create service

    When you create services the most important thing is binding and binding is also frequently asked  by an interviewer so please read carefully...this article focuses on practice part ,Theory Parts are described in the next article.

    In this article we take four different layers  (follow 3 tier architecture),

    layer

    Breadcrumbs

    follows this Step: File>>New>>Project>>WCF>>WCF Application.

    code

Create three different layers

  1. WCFServices_BEL: this is entity layer for create entities...like Usermaster.
    1. [DataContract]  
    2. public class Response  
    3. {  
    4.     [DataMember]  
    5.     public int ? UserId  
    6.     {  
    7.             get;  
    8.             set;  
    9.         }  
    10.         [DataMember]  
    11.     public string UserName  
    12.     {  
    13.         get;  
    14.         set;  
    15.     }  
    16.     [DataMember]  
    17.     public string FirstName  
    18.     {  
    19.         get;  
    20.         set;  
    21.     }  
    22.     [DataMember]  
    23.     public string LastName  
    24.     {  
    25.         get;  
    26.         set;  
    27.     }  
    28.     [DataMember]  
    29.     public string FatherName  
    30.     {  
    31.         get;  
    32.         set;  
    33.     }  
    34.     [DataMember]  
    35.     public string MotherName  
    36.     {  
    37.         get;  
    38.         set;  
    39.     }  
    40.     [DataMember]  
    41.     public string FirstDigitInd  
    42.     {  
    43.         get;  
    44.         set;  
    45.     }  
    46.     [DataMember]  
    47.     public string SecondDigitInd   
    48.     {  
    49.         get;  
    50.         set;  
    51.     }  
    52.     [DataMember]  
    53.     public string DisplayName  
    54.     {  
    55.         get;  
    56.         set;  
    57.     }  
    58.     [DataMember]  
    59.     public string Gender  
    60.     {  
    61.         get;  
    62.         set;  
    63.     }  
    64.     [DataMember]  
    65.     public string MobileNumber  
    66.     {  
    67.         get;  
    68.         set;  
    69.     }  
    70.     [DataMember]  
    71.     public string PinCode   
    72.     {  
    73.         get;  
    74.         set;  
    75.     }  
    76.     [DataMember]  
    77.     public string Pin {  
    78.         get;  
    79.         set;  
    80.     }  
    81.     [DataMember]  
    82.     public int ? Age {  
    83.         get;  
    84.         set;  
    85.     }  
    86. }  

    If your application does not find DataMember and throws any compile time exception that means it did not find namespace in WCFServices_BEL layer for DataMember so please add namespace,

    using System.Runtime.Serialization;

    serial

  2. WCFServices_DAL:

    This is DAL layer for CRUD (Create,Read,Update & Delete ) operation, Let’s explain ValidateLogin method.it has two input parameters, UserName and Password, and returns all field of user...for fetching user information simply use   ado.net (C#).
    1. #region LoginUser  
    2.   
    3. public Response ValidateLogin(string UserName, string Password)  
    4. {  
    5.     Response response = new Response();  
    6.     ObjCmd = new SqlCommand();  
    7.     objCommonDAO = new CommonDAO();  
    8.     ObjCmd.CommandText = "ValidateLogin";  
    9.     ObjCmd.CommandType = CommandType.StoredProcedure;  
    10.     ObjCmd.Parameters.AddWithValue("@UserName", UserName);  
    11.     ObjCmd.Parameters.AddWithValue("@Password", Password);  
    12.     DataTable dt = new DataTable();  
    13.     SqlDataAdapter da = new SqlDataAdapter(ObjCmd);  
    14.     try  
    15.     {  
    16.         ObjCmd.Connection = objCommonDAO.GetConnection();  
    17.         da.Fill(dt);  
    18.     } finally  
    19.     {  
    20.         objCommonDAO.CloseConnection();  
    21.     }  
    22.     foreach(DataRow dr in dt.Rows)  
    23.     {  
    24.         if (dr["UserId"] != DBNull.Value) response.UserId = Convert.ToInt16(dr["UserId"]);  
    25.         response.UserName = Convert.ToString(dr["UserName"]);  
    26.         response.FirstName = Convert.ToString(dr["FirstName"]);  
    27.         response.LastName = Convert.ToString(dr["LastName"]);  
    28.         response.FatherName = Convert.ToString(dr["FatherName"]);  
    29.         response.MotherName = Convert.ToString(dr["MotherName"]);  
    30.         response.FirstDigitInd = Convert.ToString(dr["FirstDigitInd"]);  
    31.         response.DisplayName = Convert.ToString(dr["DisplayName"]);  
    32.         response.Gender = Convert.ToString(dr["Gender"]);  
    33.         response.MobileNumber = Convert.ToString(dr["MobileNumber"]);  
    34.         response.PinCode = Convert.ToString(dr["PinCode"]);  
    35.         response.Pin = Convert.ToString(dr["Pin"]);  
    36.         if (dr["Age"] != DBNull.Value) response.Age = Convert.ToInt16(dr["Age"]);  
    37.         response.SecondDigitInd = Convert.ToString(dr["SecondDigitInd"]);  
    38.   
    39.     }  
    40.     return response;  
    41. }#endregion LoginUser 
    code

  3. WCFService_POC

    This layer is most important because other layers are optiona; if you create a small service application then it's not compulsory to create all layers but it’s good practiceto  create all layers. This layer contains files used for services, first of all interface class.

    code

    In interface class all methods are created which are used in  application ..

    Eq.
    1. [OperationContract]  
    2. [WebInvoke(Method = "POST", UriTemplate = "/ValidateLogin", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]  
    3. Response ValidateLogin(string UserName, string Password);  
    Method: Get/Post/ - which method are required
    UriTemplate:- ex. "/ValidateLogin .. when call method desired name and templates
    RequestFormat and ResponseFormat :- this is type of input type and return output type
    Like json formate and xml etc.
    ServicesPOC.svc :

    public class ServicesPOC : IServicesPOC

    Interface contains only the signatures of methods, properties, events or indexers. A class or structure that implements the interface must implement the members of the interface that are specified in the interface definition.

    So create all method implementation of this class...

    Ex.
    1. ServicesDAL objServiceDL = null;  
    2. public Response ValidateLogin(string UserName, string Password)  
    3. {  
    4.     //Debugger.Launch();   
    5.     Response rs = new Response();  
    6.     //int isUser = 0;  
    7.     try {  
    8.         objServiceDL = new ServicesDAL();  
    9.         rs = objServiceDL.ValidateLogin(UserName, Password);  
    10.     } catch (Exception ex)  
    11.     {  
    12.         LoggerService.Error("""ValidateLogin : " + "\r\nError Message: " + ex.Message + "\r\nStackTrace: " + ex.StackTrace);  
    13.     }  
    14.     return rs;  
    15. }  
    LoggerService are used for write exception, Debugger.Launch(); are used for debugging you services, in this layer one more file is most important web config file Binding ex...
    1. <?xml version="1.0"?>  
    2. <configuration>  
    3.   
    4.     <system.web>  
    5.         <trust level="Full" />  
    6.         <customErrors mode="RemoteOnly" />  
    7.         <compilation debug="true" targetFramework="4.0" />  
    8.         <httpRuntime />  
    9.         <pages controlRenderingCompatibilityVersion="4.0" />  
    10.     </system.web>  
    11.     <system.webServer>  
    12.         <validation validateIntegratedModeConfiguration="false" />  
    13.         <modules runAllManagedModulesForAllRequests="true" />  
    14.         <directoryBrowse enabled="true" />  
    15.     </system.webServer>  
    16.     <system.serviceModel>  
    17.         <bindings>  
    18.             <webHttpBinding>  
    19.                 <binding name="webBinding" maxReceivedMessageSize="10485760" maxBufferPoolSize="10485760" maxBufferSize="10485760" closeTimeout="00:03:00" openTimeout="00:03:00" receiveTimeout="00:10:00" sendTimeout="00:03:00">  
    20.                     <readerQuotas maxDepth="32" maxStringContentLength="10485760" maxArrayLength="10485760" maxBytesPerRead="10485760" />  
    21.                     <security mode="None">  
    22.                         <transport clientCredentialType="None" />  
    23.                     </security>  
    24.                 </binding>  
    25.             </webHttpBinding>  
    26.         </bindings>  
    27.         <services>  
    28.             <service behaviorConfiguration="metadataBehavior" name="WCFService_POC.ServicesPOC">  
    29.                 <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" bindingConfiguration="webBinding" contract="WCFService_POC.IServicesPOC" />  
    30.             </service>  
    31.         </services>  
    32.         <behaviors>  
    33.             <endpointBehaviors>  
    34.                 <behavior name="web">  
    35.                     <webHttp helpEnabled="true" />  
    36.                 </behavior>  
    37.                 <behavior name="EventServiceAspNetAjaxBehavior">  
    38.                     <enableWebScript />  
    39.                 </behavior>  
    40.             </endpointBehaviors>  
    41.             <serviceBehaviors>  
    42.                 <behavior name="metadataBehavior">  
    43.                     <serviceMetadata httpGetEnabled="true" />  
    44.                     <serviceDebug includeExceptionDetailInFaults="true" />  
    45.                 </behavior>  
    46.                 <behavior name="">  
    47.                     <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />  
    48.                     <serviceDebug includeExceptionDetailInFaults="false" />  
    49.                 </behavior>  
    50.             </serviceBehaviors>  
    51.         </behaviors>  
    52.   
    53.         <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="false" />  
    54.     </system.serviceModel>  
    55.   
    56.     <appSettings>sdad  
    57.         <add key="connectionstring" value="server=server Name ;database=App_Service;user id=sa;password= password;max pool size=2000;" />  
    58.   
    59.     </appSettings>  
    60.   
    61. </configuration>  

Above

Config file remember two thing --  first one is how to create behaviour,

  1. <behavior name="metadataBehavior">  
  2. <serviceMetadata httpGetEnabled="true" />  
  3. <serviceDebug includeExceptionDetailInFaults="true" />  
  4. </behavior>  
And second one is how to create services config,
  1. <services>  
  2. <service behaviorConfiguration="metadataBehavior" name="WCFService_POC.ServicesPOC">  
  3. <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"  
  4. bindingConfiguration="webBinding" contract="WCFService_POC.IServicesPOC" />  
  5. </service>  
  6. </services>  
Notes: Different ways to debug a service.

 

  1. Attaching the debugger to the services's process ( Need to INSTALL the service).
  2. Using 'Debugger.Launch() / Debugger.Break()' methods ( Need to INSTALL the service)
  3. Calling the OnStart() method from another Main() function ( DO NOT need to INSTALL the service)
    Also we used postman ,fiddler etc......Thank You

    history


Similar Articles