Creating Self Hosted ASP.NET Web API With CRUD Operations In Visual Studio 2010


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



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,

Hide Copy Code
  1. USE[WebApiDb]    
  2. /****** Object Table [dbo].[Products] Script Date    
  3. 04/14/2016 110251 ******/    
  5. GO     
  7. GO     
  9. GO     
  10. CREATE TABLE[dbo].[Products](    
  11. [ProductId][int]     
  12. IDENTITY(1, 1) NOT NULL,     
  13. [ProductName][varchar](50) NOT     
  14. NULL,      
  16. [ProductId] ASC      
  18. WITH(PAD_INDEX = OFF,     
  21. ON[PRIMARY]     
  22. GO     
  24. GO    
So we are done with database creation, now let us set up the entity layer for communication.

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 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

Hide Shrink Copy Code
  1. using System;    
  2. usingSystem.Collections.Generic;    
  3. usingSystem.Linq;    
  4. using System.Net;    
  5. usingSystem.Net.Http;    
  6. usingSystem.Web.Http;    
  8. namespaceSelfHostedAPI    
  9.  {    
  10. publicclassProductController ApiController    
  11.      {    
  12. // GET api/<controller>    
  13. publicIEnumerable<string>Get()    
  14.          {    
  15. returnnewstring[] { "value1""value2" };    
  16.          }    
  18. // GET api/<controller>/5    
  19. publicstringGet(int id)    
  20.          {    
  21. return"value";    
  22.          }    
  24. // POST api/<controller>    
  25. publicvoidPost([FromBody]stringvalue)    
  26.          {    
  27.          }    
  29. // PUT api/<controller>/5    
  30. publicvoidPut(int id, [FromBody]stringvalue)    
  31.          {    
  32.          }    
  34. // DELETE api/<controller>/5    
  35. publicvoidDelete(int id)    
  36.          {    
  37.          }    
  38.      }    
  39.  }    
We’ll make use of these default methods but write our own business logic for DB operations.

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.

Hide Copy Code
  1. // GET api/<controller>    
  2. publicIEnumerable<Product>Get()    
  3.          {    
  4. var entities=newWebApiDbEntities();    
  5. returnentities.Products;    
  6.          }    
In the above mentioned code base we return 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.

Hide Copy Code
  1. // GET api/<controller>/5    
  2. public Product Get(int id)    
  3.         {    
  4. var entities = newWebApiDbEntities();    
  5. returnentities.Products.FirstOrDefault(p=>p.ProductId==id);    
  6.         }    
3. Create product

Hide Copy Code
  1. // POST api/<controller>    
  2. publicboolPost([FromBody]Product product)    
  3.         {    
  4. var entities = newWebApiDbEntities();    
  5. entities.AddToProducts(product);    
  6. vari = entities.SaveChanges();    
  7. returni> 0;    
  8.         }    

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

Hide Copy Code
  1. // PUT api/<controller>/5    
  2. publicboolPut(int id, [FromBody]Product product)    
  3.       {    
  4. using (var entities = newWebApiDbEntities())    
  5.           {    
  6. var prod = (from p inentities.Products    
  7. wherep.ProductId == id    
  8.                           select p).FirstOrDefault();    
  10. prod.ProductName = product.ProductName;    
  11. vari=entities.SaveChanges();    
  12. returni> 0;    
  13.           }    
  14.       }   
 Since this is an update operation, we name it as 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

Hide Copy Code
  1. // DELETE api/<controller>/5    
  2. publicboolDelete(int id)    
  3.          {    
  4. using (var entities = newWebApiDbEntities())    
  5.              {    
  6. var prod = (from p inentities.Products    
  7. wherep.ProductId == id    
  8.                              select p).FirstOrDefault();    
  10. entities.Products.DeleteObject(prod);    
  11. vari=entities.SaveChanges();    
  12. returni> 0;    
  13.              }    
  14.          }    

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,

Hide Copy Code
  1. 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

Hide Copy Code
  1. 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

Hide Copy Code

    1. netsh http delete urlacl url=http//+8080/"   
1. Define an object for SelfHostConfiguration as follows,

Copy Code
  1. var config = new HttpSelfHostConfiguration("http//localhost8082");     

2. Define the default route of your WebAPI,

Hide Copy Code
  1. config.Routes.MapHttpRoute(    
  2. "API Default""api/{controller}/{id}",    
  3. new{ id = RouteParameter.Optional });   

This is the default route that our service will follow while running.

3. Start server in a process

Hide Copy Code
  1. using (var server = newHttpSelfHostServer(config))    
  2.   {    
  3. server.OpenAsync().Wait();    
  4. Console.WriteLine("Server started....");    
  5. Console.WriteLine("Press Enter to quit.");    
  6. Console.ReadLine();    
  7.   }    

The above piece of code is used to host and start a server for the service that we have created. As you can see its just few lines of code to get our service started in a separate process and we don’t actually need to rely upon IIS server.

Hence our Program.cs becomes.

Hide Copy Code
  1. using System;    
  2. usingSystem.Web.Http;    
  3. usingSystem.Web.Http.SelfHost;     
  5. namespaceSelfHostedAPI    
  6.  {    
  7. class Program    
  8.      {    
  9. staticvoidMain(string[] args)    
  10.          {    
  11. varconfig = newHttpSelfHostConfiguration("http//localhost8082");    
  13. config.Routes.MapHttpRoute(    
  14. "API Default""api/{controller}/{id}",    
  15. new{ id = RouteParameter.Optional });    
  17. using (var server = newHttpSelfHostServer(config))    
  18.              {    
  19. server.OpenAsync().Wait();    
  20. Console.WriteLine("Server started....");    
  21. Console.WriteLine("Press Enter to quit.");    
  22. Console.ReadLine();    
  23.              }    
  24.          }    
  25.      }    
  26.  }    

Now when you start the application by pressing F5, you’ll get your server started and service endpoints listening to your request. We’ll test the end points with our own test client that we are about to create. But before that let us start our server.

Compile the application and in windows explorer navigate to SelfHostedAPI.exe in the bin\debug folder and run it as an administrator.

You server will start immediately.

And when you type the URL in browser http//localhost8082, you’ll see that the server actually returns a response of resource not found,

That means our port is listening to the requests.

WebAPI Test Client

Now that we know our services are up and running, its time to test them through a test client. You can use your own test client or build a one as a console application. I am building a separate test client in .NET itself to test the services.

Step 1: Add a console application

Add a console application in the same or another solution with the name APITestClient or the name of your choice. We’ll use Program.cs to write all the code for calling WebAPI methods. But before that we need to install a nuget package that helps us in creating a httpclient through which we’ll make API calls.

Step 2: Add web client package

Open Library package manager, select APITestClient as default project and execute the command "Install-Package Microsoft.AspNet.WebApi.Client -Version 4.0.20710"

This will install the necessary package and its dependencies in your test client project.

Step 3: Setup client

Time to the code, open program.cs and add namespace

Hide Copy Code
  1. using System.Net.Http;     
  2. using System.Net.Http.Headers; 

Define HttpClient variable,

Hide Copy Code
  1. private static readonly HttpClient Client = new HttpClient();   
and in the Main method initialize the client with basic requirements like with the base address of services to be called and media type,
Hide Copy Code
  1. Client.BaseAddress = newUri("http//localhost8082");    
  2. Client.DefaultRequestHeaders.Accept.Clear();    
  3. Client.DefaultRequestHeaders.Accept.Add(newMediaTypeWithQualityHeaderValue("application/json"));    

All set, now we can write CRUD calling methods and call them from main method.

Step 4: Calling Methods

1. GetAllProducts:

Hide Copy Code
  1. /// <summary>    
  2. /// Fetch all products    
  3. /// </summary>    
  4. privatestaticvoidGetAllProducts()    
  5.         {    
  6. HttpResponseMessageresp = Client.GetAsync("api/product").Result;    
  7. resp.EnsureSuccessStatusCode();    
  9. var products = resp.Content.ReadAsAsync<IEnumerable<SelfHostedAPI.Product>>().Result.ToList();    
  10. if (products.Any())    
  11.             {    
  12. Console.WriteLine("Displaying all the products...");    
  13. foreach (var p in products)    
  14.                 {    
  15. Console.WriteLine("{0} {1} ", p.ProductId, p.ProductName);    
  16.                 }    
  17.             }    
  18.         } 

The above method makes call to "api/product" endpoint via HttpClient instance and expects a result in HttpResponseMessage from service. Note that it uses the method GetAsync to make an endpoint call, this states that it is calling a Get method of REST API.

We have about six records in database that need to be displayed


Let’s run the application by calling the method from the Main method but before that make sure your WebAPI is running in the console application like we did earlier

Hide Copy Code
  1. privatestaticvoidMain(string[] args)    
  2.  {    
  3. Client.BaseAddress = newUri("http//localhost8082");    
  4. Client.DefaultRequestHeaders.Accept.Clear();    
  5. Client.DefaultRequestHeaders.Accept.Add(newMediaTypeWithQualityHeaderValue("application/json"));    
  6. GetAllProducts();    
  8. Console.WriteLine("Press Enter to quit.");    
  9. Console.ReadLine();    
  10.  }   
The result is shown below.

Hurray, we got all our products from database to this client.

This proves that our service is well hosted and working fine. We can define other methods too in a similar way and test the API endpoints.

2. GetProduct()

This method fetches product by id.

Hide Copy Code
  1. /// <summary>    
  2. /// Get product by id    
  3. /// </summary>    
  4. privatestaticvoidGetProduct()    
  5.  {    
  6. constint id = 1;    
  7. varresp = Client.GetAsync(string.Format("api/product/{0}", id)).Result;    
  8. resp.EnsureSuccessStatusCode();    
  10. var product = resp.Content.ReadAsAsync<SelfHostedAPI.Product>().Result;    
  11. Console.WriteLine("Displaying product having id  " + id);    
  12. Console.WriteLine("ID {0} {1}", id, product.ProductName);    
  13.  }    

Again the method is self explanatory. I have by default called this method for product id "1" you can customize the method as per your need. Just compile and run the method. We get,


Hence we get the result.

3. AddProduct()

Hide Copy Code
  1. /// <summary>    
  2. /// Add product    
  3. /// </summary>    
  4. privatestaticvoidAddProduct()    
  5.         {    
  6. varnewProduct = newProduct() { ProductName = "Samsung Phone" };    
  7. var response = Client.PostAsJsonAsync("api/product", newProduct);    
  8. response.Wait();    
  9. if (response.Result.IsSuccessStatusCode)    
  10.             {    
  11. Console.WriteLine("Product added.");    
  12.             }    
  13.         }   
In the above method I am trying to add a new product named "Samsung Phone" in our existing product list. Since we have auto id generation at database, we don’t have to provide the id of the product. It will automatically get inserted in the database with a unique id. Note that this method makes a call with a Post type method to API end point. Run the application.

It says product added. Now let’s go to the database and check our table. Execute a select query over your table in the SQL Server database and we get one new product with id "7" added in the table having name "Samsung Phone,"


4. EditProduct()

Hide Copy Code
  1. /// <summary>    
  2. /// Edit product     
  3. /// </summary>    
  4. privatestaticvoidEditProduct()    
  5.         {    
  6. constintproductToEdit = 4;    
  7. var product = newProduct() { ProductName = "Xamarin" };    
  9. var response =    
  10. Client.PutAsJsonAsync("api/product/" + productToEdit, product);    
  11. response.Wait();    
  12. if (response.Result.IsSuccessStatusCode)    
  13.             {    
  14. Console.WriteLine("Product edited.");    
  15.             }    
  17.         }    

In the above code I am editing a product having the product id "4" and changing the existing product name i.e. iPad to Xamarin. Note that this method makes a call with a Put type method to API end point. Run the application.

In the database

We see here that our existing product named iPad is updated to new name "Xamarin." We see that one new product has also been added with the id 8. That’s because we again called the add method from main method. Ideally we would have commented it out while testing the edit method.

5. DeleteProduct()

Hide Copy Code
  1. /// <summary>    
  2. /// Delete product    
  3. /// </summary>    
  4. privatestaticvoidDeleteProduct()    
  5.      {    
  6. constintproductToDelete = 2;    
  7. var response = Client.DeleteAsync("api/product/" + productToDelete);    
  8. response.Wait();    
  9. if (response.Result.IsSuccessStatusCode)    
  10.          {    
  11. Console.WriteLine("Product deleted.");    
  12.          }    
  13.      }  

In the above method we delete a product having id 2. Note that this method makes a call with a Delete type method to the API end point. Run the application.

Product deleted. Let’s check in database,


We see product with id "2" as deleted.

So we have performed all the CRUD operations on a self hosted WebAPI. And the result was as expected. The following is the code for Program.cs file in consolidation.

Hide Shrink Copy Code 
  1. #region Using namespaces    
  2. using System;    
  3. usingSystem.Collections.Generic;    
  4. usingSystem.Linq;    
  5. usingSystem.Net.Http;    
  6. usingSystem.Net.Http.Headers;    
  7. usingSelfHostedAPI;     
  8. #endregion    
  10. namespaceAPITestClient    
  11.  {    
  12. internalclass Program    
  13.      {    
  14. #region Private member variables    
  15. privatestaticreadonlyHttpClient Client = newHttpClient();     
  16. #endregion    
  18. #region Main method for execution entry    
  19. /// <summary>    
  20. /// Main method    
  21. /// </summary>    
  22. /// <param name="args"></param>    
  23. privatestaticvoidMain(string[] args)    
  24.          {    
  25. Client.BaseAddress = newUri("http//localhost8082");    
  26. Client.DefaultRequestHeaders.Accept.Clear();    
  27. Client.DefaultRequestHeaders.Accept.Add(newMediaTypeWithQualityHeaderValue("application/json"));    
  28. GetAllProducts();    
  29. GetProduct();    
  30. AddProduct();    
  31. EditProduct();    
  32. DeleteProduct();    
  33. Console.WriteLine("Press Enter to quit.");    
  34. Console.ReadLine();    
  35.          }     
  36. #endregion    
  38. #region Private client methods    
  39. /// <summary>    
  40. /// Fetch all products    
  41. /// </summary>    
  42. privatestaticvoidGetAllProducts()    
  43.          {    
  44. HttpResponseMessageresp = Client.GetAsync("api/product").Result;    
  45. resp.EnsureSuccessStatusCode();    
  47. var products = resp.Content.ReadAsAsync<IEnumerable<SelfHostedAPI.Product>>().Result.ToList();    
  48. if (products.Any())    
  49.              {    
  50. Console.WriteLine("Displaying all the products...");    
  51. foreach (var p in products)    
  52.                  {    
  53. Console.WriteLine("{0} {1} ", p.ProductId, p.ProductName);    
  54.                  }    
  55.              }    
  56.          }    
  58. /// <summary>    
  59. /// Get product by id    
  60. /// </summary>    
  61. privatestaticvoidGetProduct()    
  62.          {    
  63. constint id = 1;    
  64. varresp = Client.GetAsync(string.Format("api/product/{0}", id)).Result;    
  65. resp.EnsureSuccessStatusCode();    
  67. var product = resp.Content.ReadAsAsync<SelfHostedAPI.Product>().Result;    
  68. Console.WriteLine("Displaying product having id  " + id);    
  69. Console.WriteLine("ID {0} {1}", id, product.ProductName);    
  70.          }    
  72. /// <summary>    
  73. /// Add product    
  74. /// </summary>    
  75. privatestaticvoidAddProduct()    
  76.          {    
  77. varnewProduct = newProduct() { ProductName = "Samsung Phone" };    
  78. var response = Client.PostAsJsonAsync("api/product", newProduct);    
  79. response.Wait();    
  80. if (response.Result.IsSuccessStatusCode)    
  81.              {    
  82. Console.WriteLine("Product added.");    
  83.              }    
  84.          }    
  86. /// <summary>    
  87. /// Edit product     
  88. /// </summary>    
  89. privatestaticvoidEditProduct()    
  90.          {    
  91. constintproductToEdit = 4;    
  92. var product = newProduct() { ProductName = "Xamarin" };    
  94. var response =    
  95. Client.PutAsJsonAsync("api/product/" + productToEdit, product);    
  96. response.Wait();    
  97. if (response.Result.IsSuccessStatusCode)    
  98.              {    
  99. Console.WriteLine("Product edited.");    
  100.              }    
  102.          }    
  104. /// <summary>    
  105. /// Delete product    
  106. /// </summary>    
  107. privatestaticvoidDeleteProduct()    
  108.          {    
  109. constintproductToDelete = 2;    
  110. var response = Client.DeleteAsync("api/product/" + productToDelete);    
  111. response.Wait();    
  112. if (response.Result.IsSuccessStatusCode)    
  113.              {    
  114. Console.WriteLine("Product deleted.");    
  115.              }    
  116.          }    
  118. #endregion    
  119.      }    
  120.  }    

I have tried to keep this tutorial simple and straightforward, and explain each and every step through which you can create a simple WebAPI with all CRUD operations using Entity Framework, and finally self host that API and test it. I hope you enjoyed reading this article. You can download the complete source code from github.

Read more

Other Series

My other series of articles

Up Next
    Ebook Download
    View all
    View all