How to create WCF service with IIS hosting?

In Visual Studio go to "File" -> "New" -> "Project..." then select "C#" -> "WCF" -> "WCF Service Library".
Now set the name of the project as "ProductServiceLibrary" then click "OK".
WCF1.jpg
In the next step change the name of the files:
From "IService.cs" to "IProductService.cs"
WCF2.jpg
Now in "IProductService.cs" write the following code to implement it with the Service Class i.e. "ProductService.cs":
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.Serialization;
  5. using System.ServiceModel;
  6. using System.Text;
  7. namespace ProductServiceLibrary
  8. {
  9. [ServiceContract]
  10. public interface IProductService
  11. {
  12. [OperationContract]
  13. List<Product> GetAllProduct();
  14. [OperationContract]
  15. Product GetProductByID(string ProductId);
  16. }
  17. [DataContract]
  18. public class Product
  19. {
  20. [DataMember]
  21. public int ProductID
  22. {
  23. get;
  24. set;
  25. }
  26. [DataMember]
  27. public string ProductName
  28. {
  29. get;
  30. set;
  31. }
  32. [DataMember]
  33. public string QuantityPerUnit
  34. {
  35. get;
  36. set;
  37. }
  38. [DataMember]
  39. public decimal UnitPrice
  40. {
  41. get;
  42. set;
  43. }
  44. }
  45. }
After creating the interface we must implement it and must write code for the service.
WCF3.jpg
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.Serialization;
  5. using System.ServiceModel;
  6. using System.Text;
  7. namespace ProductServiceLibrary
  8. {
  9. public class ProductService : IProductService
  10. {
  11. public List<Product> GetAllProduct()
  12. {
  13. throw new NotImplementedException();
  14. }
  15. public Product GetProductByID(string ProductId)
  16. {
  17. throw new NotImplementedException();
  18. }
  19. }
  20. }
Now we have implemented the IProductService interface with the Service.
We must write the code to get all the products from the database and one product detail by product ID.
But before this we will set the database connection string in the Project property.
WCF4.jpg
WCF5.jpg
WCF6.jpg
After clicking "Ok" open the "App.config" file and we will see the database connection string.
WCF7.jpg
After setting the connection string in the project properties, now we will write code to access the data from the database in the methods we implemented.
So here is the code:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.Serialization;
  5. using System.ServiceModel;
  6. using System.Text;
  7. using System.Data.SqlClient;
  8. namespace ProductServiceLibrary
  9. {
  10. public class ProductService : IProductService
  11. {
  12. public List<Product> GetAllProduct()
  13. {
  14. List<Product> Products = new List<Product>();
  15. using (SqlConnection con = new SqlConnection(Properties.Settings.Default.ConStr))
  16. {
  17. using (SqlCommand cmd = new SqlCommand("Select ProductId,ProductName,QuantityPerUnit,UnitPrice from Products", con))
  18. {
  19. con.Open();
  20. SqlDataReader dr = cmd.ExecuteReader();
  21. while (dr.Read())
  22. {
  23. Product product = new Product();
  24. product.ProductID = dr.GetInt32(0);
  25. product.ProductName = dr.GetString(1);
  26. product.QuantityPerUnit = dr.GetString(2);
  27. product.UnitPrice = dr.GetDecimal(3);
  28. Products.Add(product);
  29. }
  30. }
  31. }
  32. return Products;
  33. }
  34. public Product GetProductByID(string ProductId)
  35. {
  36. Product product = new Product();
  37. using (SqlConnection con = new SqlConnection(Properties.Settings.Default.ConStr))
  38. {
  39. using (SqlCommand cmd = new SqlCommand("Select ProductId,ProductName,QuantityPerUnit,UnitPrice from Products", con))
  40. {
  41. con.Open();
  42. SqlDataReader dr = cmd.ExecuteReader();
  43. while (dr.Read())
  44. {
  45. product.ProductID = dr.GetInt32(0);
  46. product.ProductName = dr.GetString(1);
  47. product.QuantityPerUnit = dr.GetString(2);
  48. product.UnitPrice = dr.GetDecimal(3);
  49. }
  50. }
  51. }
  52. return product;
  53. }
  54. }
  55. }
Now our first WCF has been created. It is time to test our WCF Service Application; just press the F5 button.
The WCF Test Client will run.
WCF8.jpg
Select the method "GetAllProduct" and click "Invoke".
WCF9.jpg
The preceding screen is the indication that the f WCF Service was created successfully.
Now our second step is just to host this WCF Application using IIS.
Click on the solution then right-click then select "Add" -> "New Website".
WCF10.jpg
WCF11.jpg
After clicking "OK" the Website application will be added to the solution. Then after it has been added it, two extra files will get generated in the project, i.e. "IService.cs" & "Service.cs". We have, however, already created these file in the WCF Library, so now we will delete them and add the reference to "ProductServiceLibrary.dll".
WCF12.jpg
Add the reference to the ProductServiceLibrary.dll in this project.
WCF13.jpg
WCF14.jpg
WCF15.jpg
Now open the Service.svc file.
Delete the selected code (in the following image) and the reason is very simple, because in our ProductServiceLibrary.dll we created the ProductService.cs and in the current project we have deleted the Service.cs file from the App_code folder.
And replace the current line with this line of code:
  1. <%@ ServiceHost Language="C#" Debug="true" Service="ProductServiceLibrary.ProductService" %>
WCF16.jpg
We have altered the .svc file and it is time to add the End Points to Web.Config, as in:
  1. <?xml version="1.0"?>
  2. <configuration>
  3. <system.web>
  4. <compilation debug="false" targetFramework="4.0" />
  5. </system.web>
  6. <system.serviceModel>
  7. <services>
  8. <service name="ProductServiceLibrary.ProductService">
  9. <endpoint address="" binding="wsHttpBinding" contract="ProductServiceLibrary.IProductService">
  10. <identity>
  11. <dns value="localhost" />
  12. </identity>
  13. </endpoint>
  14. <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  15. </service>
  16. </services>
  17. <behaviors>
  18. <serviceBehaviors>
  19. <behavior>
  20. <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
  21. <serviceMetadata httpGetEnabled="true"/>
  22. <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
  23. <serviceDebug includeExceptionDetailInFaults="false"/>
  24. </behavior>
  25. </serviceBehaviors>
  26. </behaviors>
  27. <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  28. </system.serviceModel>
  29. <system.webServer>
  30. <modules runAllManagedModulesForAllRequests="true"/>
  31. </system.webServer>
  32. </configuration>
After adding the End Points in the web.config file, our hosting task is finished. Now it is time to test the Hosting Application.
For that please use the following steps in the following image:
WCF17.jpg
WCF18.jpg
WCF19.jpg
The preceding color full page is the indication of successfully hosting WCF in IIS.
Now our next step is to consume this WCF IIS hosted service in a client application and this is a very easy task.

Consume WCF IIS hosted service

So let's proceed to our last step.
WCF20.jpg
WCF21.jpg
WCF22.jpg
WCF23.jpg
WCF24.jpg
WCF25.jpg
WCF26.jpg
On the Default.aspx.cs page write the code:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using ProductWebClient.ProductServiceClient;
  8. namespace ProductWebClient
  9. {
  10. public partial class Default : System.Web.UI.Page
  11. {
  12. protected void Page_Load(object sender, EventArgs e)
  13. {
  14. }
  15. protected void BtnAdd_Click(object sender, EventArgs e)
  16. {
  17. ProductServiceClient.ProductServiceClient proxy = new ProductServiceClient.ProductServiceClient();
  18. ProductGridView.DataSource= proxy.GetAllProduct();
  19. ProductGridView.DataBind();
  20. }
  21. }
  22. }
Now run the application, except before doing that do one more last task.
WCF27.jpg
WCF28.jpg
Set the ProductWebClient as "Set as StartUp Project" and press F5 and here is the result.
ENJOY!