Introduction
I have been writing a lot about WebAPIs in my Learning WebAPI series, but one crucial topic that I missed was hosting an ASP.NET WebAPI .
Hosting a WebAPI in IIS is pretty straightforward and is more similar to how you host a typical ASP.NET web application. In this article, I’ll explain how we can host a WebAPI in another process independent of IIS.
I’ll explain how to quickly create a WebAPI having CRUD operations with Entity Framework 4.0 and then host it on an independent server. I’ll call the service end points through a console application acting as a client. You can use any client to check the service end points and verify their functionality. I’ll try to explain the topic with practical implementations, then create a service and a test client in Visual Studio 2010 around a target framework such as .NET Framework 4.0.

WebAPI project
The traditional way of creating an ASP.NET REST service is to select a WebAPI project from Visual Studio, create a controller, expose endpoints and host that on IIS. But when it comes to creating a self-hosted web API on Windows, we need to take a windows or a console based application, that generates an EXE when compiled which in turn can be used for hosting through a command prompt. You can host WebAPI 2 with OWIN and that is very straightforward with the help of two NuGet packages mentioned below
Microsoft.Owin.SelfHost
Microsoft.AspNet.WebApi.OwinSelfHost
But we’ll do hosting for WebAPI 1 and will not make use of OWINn for this application.
Step 1: Create Console Application
Open your Visual Studio and create a new console application named SelfHostedAPI,

We’ll add a WebAPI controller to it and write code for CRUD operations, but before that we need a database and a communication for performing database transactions. I’ll use EntityFramework for database transactions.
Step 2: Create Database
You can create any database you want. I am using SQL Server and will create a database named WebAPIdb having a table named Products for performing CRUD operations. There are more tables in this database but we’ll not use them.

I’ll provide that database script along with this article. Script for Products table is as follows,
- USE[WebApiDb]
- /****** Object Table [dbo].[Products] Script Date
- 04/14/2016 110251 ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- SET ANSI_PADDING ON 1
- GO
- CREATE TABLE[dbo].[Products](
- [ProductId][int]
- IDENTITY(1, 1) NOT NULL,
- [ProductName][varchar](50) NOT
- NULL,
- CONSTRAINT[PK_Products] PRIMARY KEY CLUSTERED
- [ProductId] ASC
- ) WITH(PAD_INDEX = OFF,
- STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS
- = ON, ALLOW_PAGE_LOCKS = ON) ON[PRIMARY]
- ) ON[PRIMARY]
- GO
- SET ANSI_PADDING OFF
- GO
Step 3: Set up data access using Entity Framework
In your Visual Studio, select Tool->Packet Manager->Packet Manager Console to add Entity framework package,

I’ll install Entity Framework 5.0, as it works well with .NET Framework 4.0. So select SelfHostedAPI as the Default project and type the command,
Install-Package EntityFramework –Version 5.0.0 and press enter.

Once installed successfully, you’ll see Entity framework dll added to your project.
Now right click your project and add new item. Select ADO.Net Entity Data Model from list of Visual C# items.

You’ll be prompted with options to generate model. Choose Generate From Database option and proceed.

After providing database details in the next step, choose the database tables that you want to map with the model. I have only selected the products table as we’ll perform CRUD over this table only.

Click on Finish and your Entity Data Model will be ready with your database tables mapping. You’ll see that anApp.Config file is generated and a connection string specific to the selected database is added to that config file.
Now we need to generate an object context that handles transactions and objectset acting as model classes mapped to the table.
Right click on your edmx view and in the context menu, click Add Code Generation Item.

In the open window for list of items select ADO.NET EntityObject Generator as shown in the image below.

Select this and press OK, this will generate your Model1.tt class containing context and entities in the same class. Now we are done with all database related stuff. I’ll now create a WebAPI controller and in place all CRUD operations in it.
Step 4: Add WebAPI Controller
Since we need an API where we can perform all CURD operations on our database, we have to add a WebAPI controller class in the project. Since this is a console application and not a WebAPI project we don’t have a proper structure defined for adding controller. You can create your own folder structure for the sake of understanding. I am directly adding an API controller class named ProductController in the project.
Right click on project, add a new item and select WebAPI controller class from the list of items. You can name it whatever you choose. I have named it ProductController

The generated class is derived from the APIController class. That means it is a valid WebAPI controller class. The class by default contains default CRUD methods that have the following implementations
Copy Code- using System;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- using System.Net;
- usingSystem.Net.Http;
- usingSystem.Web.Http;
- namespaceSelfHostedAPI
- {
- publicclassProductController ApiController
- {
- // GET api/<controller>
- publicIEnumerable<string>Get()
- {
- returnnewstring[] { "value1", "value2" };
- }
- // GET api/<controller>/5
- publicstringGet(int id)
- {
- return"value";
- }
- // POST api/<controller>
- publicvoidPost([FromBody]stringvalue)
- {
- }
- // PUT api/<controller>/5
- publicvoidPut(int id, [FromBody]stringvalue)
- {
- }
- // DELETE api/<controller>/5
- publicvoidDelete(int id)
- {
- }
- }
- }
Step 5: Add CRUD methods
We’ll add all the four methods for Create, Read, Update, and Delete. Note that we’ll not make use of any design pattern like UnitOfWork or Repository for data persistence as our main target is to self host this service and expose its CRUD endpoint.
1. Fetch All Records
Modify the Get() method to return a list of Product entities and make use of the WebAPIEntities class generated in the Model1.cs file to get list of products. The method name here signifies the type of method as well, so basically this is a Get method of the service and should be called as method type get from the client as well. The same applies to every method we write here in this class for all CRUD operations.
- // GET api/<controller>
- publicIEnumerable<Product>Get()
- {
- var entities=newWebApiDbEntities();
- returnentities.Products;
- }
IEnumerable of product entities and use object ofWebApiDbEntities (auto generated context class) to fetch all the objects using entities.Products.2. Fetch product by id
Modify Get(int id) method to return a product entity. The method takes an id and returns the product specific to that id. You can enhance the method with validations and checks to make it more robust, but for the sake of understanding the concept, I am just doing it straight away.
- // GET api/<controller>/5
- public Product Get(int id)
- {
- var entities = newWebApiDbEntities();
- returnentities.Products.FirstOrDefault(p=>p.ProductId==id);
- }
- // POST api/<controller>
- publicboolPost([FromBody]Product product)
- {
- var entities = newWebApiDbEntities();
- entities.AddToProducts(product);
- vari = entities.SaveChanges();
- returni> 0;
- }
As the name signifies, this is a Post method that fetches a Product class object from the body of the request and add that product into entities. Note that your product will be added to the actual database only when you execute entities.SaveChanges(). This method actually inserts your record in the database and returns 1 in case of successful insert else 0.
4. Edit/Update Product
- // PUT api/<controller>/5
- publicboolPut(int id, [FromBody]Product product)
- {
- using (var entities = newWebApiDbEntities())
- {
- var prod = (from p inentities.Products
- wherep.ProductId == id
- select p).FirstOrDefault();
- prod.ProductName = product.ProductName;
- vari=entities.SaveChanges();
- returni> 0;
- }
- }
Put method, and as the name signifies, it is of PUT type. The method takes the id and product object as an argument, where first an actual product from the database is fetched having the id that is passed as an argument and then that product is modified with the details of parameter product and then again saved to the database. In our case we have only product name that could be changed because id is fixed primary key, so we update the product name of a product in this method and save changes to that entity.5. Delete product
- // DELETE api/<controller>/5
- publicboolDelete(int id)
- {
- using (var entities = newWebApiDbEntities())
- {
- var prod = (from p inentities.Products
- wherep.ProductId == id
- select p).FirstOrDefault();
- entities.Products.DeleteObject(prod);
- vari=entities.SaveChanges();
- returni> 0;
- }
- }
The above mentioned delete method is of DELETE type and accepts id of the product as a parameter. The method fetches product from database w.r.t. passed id and then deletes that product and save changes. The implementation is pretty simple and self explanatory.
With this method we have completed all our CURD endpoints that we needed to expose. As you can see I have not applied any special routing for endpoints and rely upon the default routing provided by WebAPI i.e. api/<controller>/<id>
Step 6: Hosting WebAPI
Here comes the most important piece of this post, "self hosting." Remember when you created the SelfHostedAPI project, it was a console application and so it came with a Program.cs file created within the project. TheProgram.cs file contains main method i.e. entry point of the application. We’ll use this main method to write self hosting code for our WebAPI.
Before we write any code we need to add a nuget package through Package manager console. This package contains hosting specific classes required to host API in console application i.e. independently in separate process other; than IIS. Note that in WebAPI 2 we have OWIN middleware that provides this flexibility.
Since we are using Visual Studio 2010 and .NET Framework 4.0, we need to install a specific version of package named Microsoft.AspNet.WebApi.SelfHost. The compatible version that I found was version 4.0.20710,

So open your package manager console and choose default project and execute the command "Install-Package Microsoft.AspNet.WebApi.SelfHost -Version 4.0.20710"
This installs the package for your project and now you can use it for implementation.
Open the Program.cs file and add a namespace,
- using System.Web.Http.SelfHost;
and in the main method define the base address of your endpoint that you want to expose. I am choosing the endpoint to be 8082. Make sure you are running your Visual Studio in Administrator mode or else you’ll have to change a few configurations to get it to work for you. I have taken the following explanation from this ASP.NET article to explain configuration changes,
Add an HTTP URL Namespace Reservation
This application listens to http//localhost8080/. By default, listening at a particular HTTP address requires administrator privileges. When you run the tutorial, therefore, you may get this error "HTTP could not register URL http//+8080/" There are two ways to avoid this error
- Run Visual Studio with elevated administrator permissions, or
- Use Netsh.exe to give your account permissions to reserve the URL.
To use Netsh.exe, open a command prompt with administrator privileges and enter the following commandfollowing command
- netsh http add urlacl url=http//+8080/ user=machine\username
where machine\username is your user account.
When you are finished self-hosting, be sure to delete the reservation
- netsh http delete urlacl url=http//+8080/"
Hide Copy Code
- var config = new HttpSelfHostConfiguration("http//localhost8082");
2. Define the default route of your WebAPI,
- config.Routes.MapHttpRoute(
- "API Default", "api/{controller}/{id}",
- new{ id = RouteParameter.Optional });















Humayun Kabir MamunPosted Apr 17, 2016, 2:09 AM
Nice...
Vignesh ManiPosted Apr 15, 2016, 4:21 PM
Nice one
Kuppurasu NagarajPosted Apr 15, 2016, 1:20 PM
Nice Sharing..
Rahul Kumar SaxenaPosted Apr 15, 2016, 7:14 AM
good show
Debasis SahaPosted Apr 15, 2016, 5:19 AM
Good One..