---
title: "Creating a Self-Hosted WCF Service"  
description: "In this post, I’m going to explain how to create a simple WCF Service."  
author: "priyanka kushwaha"  
published: 2015-03-18  
updated: 2019-09-07  
canonical: https://www.mindstick.com/articles/1669/creating-a-self-hosted-wcf-service  
category: ".net"  
tags: ["c#", "asp.net", "wcf", "wcf hosting"]  
reading_time: 4 minutes  

---

# Creating a Self-Hosted WCF Service

In this post, I’m going to [explain](https://www.mindstick.com/forum/159699/what-is-a-compilation-error-in-dot-net-core-explain-with-an-example) how to create a simple WCF [Service](https://yourviews.mindstick.com/story/1230/top-beneficial-service-pages-of-mindstick-company).

\
**Step 1:** Open VS 2012-> file->new -> [project](https://yourviews.mindstick.com/story/1788/things-to-ensure-your-construction-project-is-successful)-> visual c# ->WCF, Name the project as ServiceOperation and Click Ok.

![Creating a Self-Hosted WCF Service](https://www.mindstick.com/mindstickarticle/7ad04f09-ff8a-411d-9282-592d48e6a536/images/2f9114f1-1eb5-48ac-8b13-28cdc6ee4ad1.png)

**Step 2:** Add new Interface IService2.cs

```
using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.ServiceModel.Web;using System.Text; namespace WCFCURDEXample{    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService2" in both code and config file together.    [ServiceContract]    public interface IService2    {         [OperationContract]         int InsertEmployee(Employee emp);        [OperationContract]              int DeleteEmployee(string EmpNo);        [OperationContract]        Employee[] GetAllEmployee();    }    [DataContract(Name = "Employee", Namespace = "")]    public class Employee    {         [DataMember]        public string EmpNo { get; set; }        [DataMember]        public string EmpName { get; set; }        [DataMember]        public string DeptNo { get; set; }        [DataMember]        public string Salary { get; set; }    }}
```

**Step 3:** Write Web.Config

*\*

*\*

```
  <connectionStrings>    <add name="cons"  connectionString="Data Source=ServerName;Initial Catalog=PriyankaDB; User Id=sa;&#xD;&#xA;Password=Password;"                       providerName="System.Data.SqlClient"/>  </connectionStrings>
```

**Step 4****:** Then Write in Service2.svc.cs

\

\

```
using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.Text;using System.Data.SqlClient;using System.Data;using System.Configuration;namespace WCFCURDEXample{    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service2" in code, svc and config file together.    // NOTE: In order to launch WCF Test Client for testing this service, please select Service2.svc or Service2.svc.cs at the Solution Explorer and start debugging.      public class Service2 : IService2    {        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["cons"].ConnectionString);        #region IService Members               public int InsertEmployee(Employee emp)        {            int result = 0;             conn.Open();            SqlCommand cmd = new SqlCommand();            cmd.Connection = conn;            cmd.CommandText = "insert into Employee values(@EmpNo,@EmpName,@salary,@deptNo)";            cmd.Parameters.AddWithValue("@EmpNo", emp.EmpNo);            cmd.Parameters.AddWithValue("@EmpName",emp.EmpName);            cmd.Parameters.AddWithValue("@Salary", emp.Salary);            cmd.Parameters.AddWithValue("@deptNo", emp.DeptNo);            result = cmd.ExecuteNonQuery();            conn.Close();            return result;        }        public int DeleteEmployee(string EmpNo)        {            int Delete = 0;            conn.Open();            SqlCommand cmd = new SqlCommand();            cmd.Connection = conn;            cmd.CommandText = "Delete  from Employee Where EmpNo=@EmpNo";           cmd.Parameters.AddWithValue("@EmpNo",EmpNo);            Delete = cmd.ExecuteNonQuery();            conn.Close();            return Delete;        }        public Employee[] GetAllEmployee()        {            List<Employee> EmpList = new List<Employee>();            conn.Open();            SqlCommand cmd = new SqlCommand("select * from Employee", conn);            SqlDataReader dr = cmd.ExecuteReader();             while (dr.Read())            {                EmpList.Add(new Employee()                {                    EmpNo = Convert.ToString(dr["EmpNo"]),                    EmpName = Convert.ToString(dr["EmpName"]),                    Salary = Convert.ToString(dr["EmpSalary"]),                    DeptNo = Convert.ToString(dr["DeptNo"])                });            }             dr.Close();            conn.Close();            return EmpList.ToArray();        }        #endregion    }}
```

**Step 5****:** Create a Web client

\

\

Create a New [Web Site](https://www.mindstick.com/articles/12285/the-finest-web-site-design-trends-you-may-expect-in-2017) using the file -> New project-> web-> [ASP.NET](https://www.mindstick.com/articles/155/concept-of-asp-dot-net) Empty Web

\

[Application](https://www.mindstick.com/articles/12824/calculator-application-in-android) -> OK

**Step 6****:** Select References ->Add Service [Reference](https://www.mindstick.com/forum/34619/call-by-value-and-call-by-reference)->select Service2.svc->OK.

*![Creating a Self-Hosted WCF Service](https://www.mindstick.com/mindstickarticle/7ad04f09-ff8a-411d-9282-592d48e6a536/images/0313dc17-990b-4bd0-9e7c-f386e08f4b71.png)*

**Step 7****:** Create a EmployeeInformation.aspx

```
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EmployeeInformation.aspx.cs" Inherits="EmployeeDetail.EmployeeInformation" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title>    <link href="css/bootstrap.min.css" rel="stylesheet" />    <link href="css/bootstrap.css" rel="stylesheet" /></head><body>    <form id="form1" runat="server">        <div class="container">            <div class="row">                <div class="col-md-6">                                        <div class="row well well-sm">                        <div class="col-md-4">                            <label for="recipient-name" class="control-label">Employee No</label>                         </div>                        <div class="col-md-4">                            <asp:TextBox ID="txtEmpNo" runat="server" CssClass="form-control"></asp:TextBox>                        </div>                    </div>                    <div class="row well well-sm">                        <div class="col-md-4">                            <label for="recipient-name" class="control-label">Employee Name</label>                         </div>                        <div class="col-md-4">                            <asp:TextBox ID="txtEmpName" runat="server" CssClass="form-control"></asp:TextBox>                        </div>                    </div>                    <div class="row well well-sm">                        <div class="col-md-4">                            <label for="recipient-name" class="control-label">Salary</label>                         </div>                        <div class="col-md-4">                            <asp:TextBox ID="txtSalary" runat="server" CssClass="form-control"></asp:TextBox>                        </div>                    </div>                    <div class="row well well-sm">                        <div class="col-md-4">                            <label for="recipient-name" class="control-label">Dept No</label>                         </div>                        <div class="col-md-4">                            <asp:TextBox ID="txtDeptNo" runat="server" CssClass="form-control"></asp:TextBox>                        </div>                    </div>                    <div class="row well well-sm">                          <div class="col-md-12">                            <asp:Button ID="btnInsert" runat="server" Text="Insert" CssClass="form-control" OnClick="btnInsert_Click" />                        </div>                                            </div>                      <div class="row well well-sm">                          <div class="col-md-12">                              <asp:Label ID="lblmsg" runat="server" Text="" CssClass="glyphicon-certificate"></asp:Label>                          </div>                      </div>                </div>                <div class="col-md-6">                    <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="GridView1_RowDeleting"  >                        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />                        <Columns>                            <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />                        </Columns>                        <EditRowStyle BackColor="#999999" />                        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />                        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />                        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />                        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />                        <SortedAscendingCellStyle BackColor="#E9E7E2" />                        <SortedAscendingHeaderStyle BackColor="#506C8C" />                        <SortedDescendingCellStyle BackColor="#FFFDF8" />                        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />                    </asp:GridView>                </div>            </div>        </div>    </form></body></html>
```

**Step 6****:** Write EmployeeInformation.aspx.cs

```
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using EmployeeDetail.ServiceReference1;using System.Net;using System.IO;using System.Text;namespace EmployeeDetail{    public partial class EmployeeInformation : System.Web.UI.Page    {        Service2Client inst;        void bindGrid()        {            inst = new Service2Client();            GridView1.DataSource = inst.GetAllEmployee();            GridView1.DataBind();        }        protected void Page_Load(object sender, EventArgs e)        {            if (!IsPostBack)            {                bindGrid();            }        }         protected void btnInsert_Click(object sender, EventArgs e)        {                      inst = new Service2Client();            Employee emp = new Employee() { EmpNo = txtEmpNo.Text, EmpName = txtEmpName.Text, Salary = txtSalary.Text, DeptNo = txtDeptNo.Text };            int res = inst.InsertEmployee(emp);            if (res > 0)                lblmsg.Text = "Successfully saved";            txtDeptNo.Text = "";            txtEmpName.Text = "";            txtEmpNo.Text = "";            txtSalary.Text = "";            bindGrid();        }              protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)        {            string  index =GridView1.Rows[e.RowIndex].Cells[3].Text;            inst = new Service2Client();          int res = inst.DeleteEmployee(index);            bindGrid();            if (res > 0)            {                lblmsg.Text = "Successfully deleted";            }        }     }}
```

**Output****:**

![Creating a Self-Hosted WCF Service](https://www.mindstick.com/mindstickarticle/7ad04f09-ff8a-411d-9282-592d48e6a536/images/29e106b2-b6a5-46cc-96ef-7aa785c4d198.png)

---

Original Source: https://www.mindstick.com/articles/1669/creating-a-self-hosted-wcf-service

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
