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
- 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),
Breadcrumbs
follows this Step: File>>New>>Project>>WCF>>WCF Application.
Create three different layers
- WCFServices_BEL: this is entity layer for create entities...like Usermaster.
- [DataContract]
- public class Response
- {
- [DataMember]
- public int ? UserId
- {
- get;
- set;
- }
- [DataMember]
- public string UserName
- {
- get;
- set;
- }
- [DataMember]
- public string FirstName
- {
- get;
- set;
- }
- [DataMember]
- public string LastName
- {
- get;
- set;
- }
- [DataMember]
- public string FatherName
- {
- get;
- set;
- }
- [DataMember]
- public string MotherName
- {
- get;
- set;
- }
- [DataMember]
- public string FirstDigitInd
- {
- get;
- set;
- }
- [DataMember]
- public string SecondDigitInd
- {
- get;
- set;
- }
- [DataMember]
- public string DisplayName
- {
- get;
- set;
- }
- [DataMember]
- public string Gender
- {
- get;
- set;
- }
- [DataMember]
- public string MobileNumber
- {
- get;
- set;
- }
- [DataMember]
- public string PinCode
- {
- get;
- set;
- }
- [DataMember]
- public string Pin {
- get;
- set;
- }
- [DataMember]
- public int ? Age {
- get;
- set;
- }
- }
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;
- 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#).
- #region LoginUser
-
- public Response ValidateLogin(string UserName, string Password)
- {
- Response response = new Response();
- ObjCmd = new SqlCommand();
- objCommonDAO = new CommonDAO();
- ObjCmd.CommandText = "ValidateLogin";
- ObjCmd.CommandType = CommandType.StoredProcedure;
- ObjCmd.Parameters.AddWithValue("@UserName", UserName);
- ObjCmd.Parameters.AddWithValue("@Password", Password);
- DataTable dt = new DataTable();
- SqlDataAdapter da = new SqlDataAdapter(ObjCmd);
- try
- {
- ObjCmd.Connection = objCommonDAO.GetConnection();
- da.Fill(dt);
- } finally
- {
- objCommonDAO.CloseConnection();
- }
- foreach(DataRow dr in dt.Rows)
- {
- if (dr["UserId"] != DBNull.Value) response.UserId = Convert.ToInt16(dr["UserId"]);
- response.UserName = Convert.ToString(dr["UserName"]);
- response.FirstName = Convert.ToString(dr["FirstName"]);
- response.LastName = Convert.ToString(dr["LastName"]);
- response.FatherName = Convert.ToString(dr["FatherName"]);
- response.MotherName = Convert.ToString(dr["MotherName"]);
- response.FirstDigitInd = Convert.ToString(dr["FirstDigitInd"]);
- response.DisplayName = Convert.ToString(dr["DisplayName"]);
- response.Gender = Convert.ToString(dr["Gender"]);
- response.MobileNumber = Convert.ToString(dr["MobileNumber"]);
- response.PinCode = Convert.ToString(dr["PinCode"]);
- response.Pin = Convert.ToString(dr["Pin"]);
- if (dr["Age"] != DBNull.Value) response.Age = Convert.ToInt16(dr["Age"]);
- response.SecondDigitInd = Convert.ToString(dr["SecondDigitInd"]);
-
- }
- return response;
- }#endregion LoginUser
- 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.
In interface class all methods are created which are used in application ..
Eq.
- [OperationContract]
- [WebInvoke(Method = "POST", UriTemplate = "/ValidateLogin", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
- 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.
- ServicesDAL objServiceDL = null;
- public Response ValidateLogin(string UserName, string Password)
- {
-
- Response rs = new Response();
-
- try {
- objServiceDL = new ServicesDAL();
- rs = objServiceDL.ValidateLogin(UserName, Password);
- } catch (Exception ex)
- {
- LoggerService.Error("", "ValidateLogin : " + "\r\nError Message: " + ex.Message + "\r\nStackTrace: " + ex.StackTrace);
- }
- return rs;
- }
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...
- <?xml version="1.0"?>
- <configuration>
-
- <system.web>
- <trust level="Full" />
- <customErrors mode="RemoteOnly" />
- <compilation debug="true" targetFramework="4.0" />
- <httpRuntime />
- <pages controlRenderingCompatibilityVersion="4.0" />
- </system.web>
- <system.webServer>
- <validation validateIntegratedModeConfiguration="false" />
- <modules runAllManagedModulesForAllRequests="true" />
- <directoryBrowse enabled="true" />
- </system.webServer>
- <system.serviceModel>
- <bindings>
- <webHttpBinding>
- <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">
- <readerQuotas maxDepth="32" maxStringContentLength="10485760" maxArrayLength="10485760" maxBytesPerRead="10485760" />
- <security mode="None">
- <transport clientCredentialType="None" />
- </security>
- </binding>
- </webHttpBinding>
- </bindings>
- <services>
- <service behaviorConfiguration="metadataBehavior" name="WCFService_POC.ServicesPOC">
- <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" bindingConfiguration="webBinding" contract="WCFService_POC.IServicesPOC" />
- </service>
- </services>
- <behaviors>
- <endpointBehaviors>
- <behavior name="web">
- <webHttp helpEnabled="true" />
- </behavior>
- <behavior name="EventServiceAspNetAjaxBehavior">
- <enableWebScript />
- </behavior>
- </endpointBehaviors>
- <serviceBehaviors>
- <behavior name="metadataBehavior">
- <serviceMetadata httpGetEnabled="true" />
- <serviceDebug includeExceptionDetailInFaults="true" />
- </behavior>
- <behavior name="">
- <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
- <serviceDebug includeExceptionDetailInFaults="false" />
- </behavior>
- </serviceBehaviors>
- </behaviors>
-
- <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="false" />
- </system.serviceModel>
-
- <appSettings>sdad
- <add key="connectionstring" value="server=server Name ;database=App_Service;user id=sa;password= password;max pool size=2000;" />
-
- </appSettings>
-
- </configuration>
Above
Config file remember two thing -- first one is how to create behaviour,
- <behavior name="metadataBehavior">
- <serviceMetadata httpGetEnabled="true" />
- <serviceDebug includeExceptionDetailInFaults="true" />
- </behavior>
And second one is how to create services config,
- <services>
- <service behaviorConfiguration="metadataBehavior" name="WCFService_POC.ServicesPOC">
- <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"
- bindingConfiguration="webBinding" contract="WCFService_POC.IServicesPOC" />
- </service>
- </services>
Notes: Different ways to debug a service.
- Attaching the debugger to the services's process ( Need to INSTALL the service).
- Using 'Debugger.Launch() / Debugger.Break()' methods ( Need to INSTALL the service)
- Calling the OnStart() method from another Main() function ( DO NOT need to INSTALL the service)
Also we used postman ,fiddler etc......Thank You