I have been writing a lot over 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 straight forward 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 CURD operations with Entity Framework 4.0 and then host it in an independent server.I’ll call the service endpoints 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 , create a service and a test client in Visual Studio 2010 around target framework as .Net Framework 4.0.
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 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 straight forward with the help of two NuGet packages mentioned below,
But we’ll do hosting for WebAPI 1 and will not make use of Owin 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 CURD operations, but before that we need the 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 CURD 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,
So we are done with database creation , now let us setup the entity layer for communication.
Step 2 : 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 Default project and type 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 the new item. Select ADO.Net Entity Data Model from a list of Visual c# items.
You’ll be prompted with options to generate a model. Choose Generate From Database option and proceed.
After providing database details in the next step, choose database tables that you want to map with the model. I have only selected products table as we’ll perform CURD over this table only.
Click on Finish and your Entity Data Model will be ready with your database tables mapping. You’ll see that an App.Config file is generated and a connection string specific to the selected database is added to that config file.
Now we need to generate 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 the list of items select ADO.NET EntityObject Generator like shown in below image.
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 CURD operations in it.
Step 3: 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, so we don’t have a proper structure defined for adding the 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 the project, add new item and select WebAPI controller class from the list of items. You can name it as per your choice. I have named it as ProductController
The generated class is derived from APIController class that means it is a valid WebAPI controller class. The class by default contains default CURD methods that have following implementations,
We’ll make use of these default methods but write our own business logic for DB operations.
Step 4: Add CURD methods
We’ll add all the four methods for Create, Update, Read 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 CURD endpoint.
1. Fetch All Records
Modify Get() method to return a list of Product entities and make use of WebAPIEntities class generated in Model1.cs file to get the 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. Same applies to every method we write here in this class for all CURD operations.
in the above-mentioned code base we return IEnumerable of product entities and use object of WebApiDbEntities (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.
3. Create product
As the name signifies, this is a Post method , that fetches a Product class object from a body of the request and adds 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 the case of successful insert else 0.
4. Edit/Update Product
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 id and product object as an argument, where first an actual product from the database is fetched having an 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 the 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
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 the 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 5: Hosting WebAPI
Here comes the most important piece of this post, “self-hosting”. Remember when you created SelfHostedAPI project, it was a console application and so it came with a Program.cs file created within the project.The Program.cs file contains the 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 a 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 the 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
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 else you’ll have to change few configurations to work it 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://localhost:8080/. 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 command:following 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/”
1. Define an object for SelfHostConfiguration as follows,
2. Define the default route of your WebAPI
This is the default route that our service will follow while running.
3. Start server in a process
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,
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 bin\debug folder and run it as an administrator.
Your server will start immediately,
And when you type the URL in browser http://localhost:8082, 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.
Step1: 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 HTTP client through which we’ll make API calls.
Step2: 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.
Step3: Setup client
Time to code, open program.cs and add the namespace ,
Define HttpClient variable,
and in Main method initialize the client with basic requirements like with base address of services to be called and media type,
All set , now we can write CURD calling methods and call them from the main method.
Step4 : Calling Methods
1. GetAllProducts :
The above method makes the 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 6 records in database that needs to be displayed,
Let’s run the application by calling the method from Main method but before that make sure your WebAPI is running in console application like we did earlier,
The result is as 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.
This method fetches product by id.
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.
In 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 the database, so ve don’t have to provide the id of the product.It will automatically get inserted in database with a unique id. Note that this method makes the 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 SQL Server database and we get one new product with id “7” added in the table having name “Samsung Phone”,
In above code, I am editing product having product id “4” and changing the existing product name i.e. IPad to Xamarin.Note that this method makes the call with a Put type method to API endpoint.Run the application
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 id 8, that’s because we again called add method from the main method , ideally, we would have commented it out while testing edit method.
In above method, we delete a product having id 2.Note that this method makes the call with a Delete type method to API endpoint.Run the application
Product deleted. Let’s check in database,
We see the product with id “2” as deleted.
So , we have performed all the CURD operations on a self-hosted WebAPI. And the result was as expected. Following is the code for Program.cs file in consolidation.
I have tried to keep this tutorial simple and straight forward, and explain each and every step through which you can create a simple WebAPI with all CURD 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.
- C# and ASP.NET Questions (All in one)
- MVC Interview Questions
- C# and ASP.NET Interview Questions and Answers
- Web Services and Windows Services Interview Questions
My other series of articles:
For more technical articles you can reach out to my personal blog CodeTeddy.