Introduction
In this article you learn about Self-Host, how we can Self-Host the ASP.NET Web API. In this article, you don't have need of the IIS server. We Host the Web API in a Console application.
Step 1
First we create the console application.
- Start Visual Studio 2012.
- Select "New Project" from the Start page.
- In the Templates, select Installed template->Visual C#.
- Select "Console application" and change name to "Hosting".
- Click on the "OK" button.
Step 2
Set the ".Net Framework 4".
- In the "Solution Explorer" right-click on the project.
- Select "Properties".
- In the "Properties windows" Select the ".Net Framework 4" From the Drop Down List of Target Folder.
- For applying the change open a prompt and click on "Yes".
Step 3
We check that the Nuget Package Manager is installed or not.
- Go to the Tools menu.
- If there is a "Library Package Manager" visible then the "Nuget Package Manager" is installed.
- If "Library Package Manager" is not visible then it is not installed.
For installation of "Nuget Package Manager":
- Go to the "Tools" menu then select "Extension and Updates".
- In the "Extension and Updates" dialog box select "Online".
- In the search box Type "nuget package manager".
- Select the "Nuget Package Manager and Install it.
Step 4
Now we install the Web API Self-Host Package.
- Go to the "Tools" menu then select "Library Package Manager" -> "Manages Nuget Packages For Solution".
- In the "Nuget Package Manager" dialog box type "Microsoft.AspNet.WebApi.SelfHost".
- Select the ASP.NET Web API Self Host and click Install.
- Click on the "I Accept" button.
Step 5
Create the Model class:
- In the "Solution Explorer".
- Right-click on the project then select "Hosting" -> "Add" -> "Class".
- Change the name of class as "Item".
- Click on the "OK" button.
Add this code in the "Item" Class:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Hosting
- {
- public class Item
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public string Category { get; set; }
- }
- }
Step 6
To add a Controller class:
- In the "Solution Explorer".
- Right-click on the project then select "Hosting" -> "Add" -> "Class".
- Change the name of the class to "ItemsController".
- Click on the "OK" button.
Add this code in the "ItemsController" class:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Web.Http;
- namespace Hosting
- {
- public class ItemsController : ApiController
- {
- Item[] items = new Item[]
- {
- new Item { Id = 1, Name = "Apple", Category = "Fruit" },
- new Item{ Id = 2, Name = "Tomato", Category = "vasitable" },
- new Item{ Id = 3, Name = "T-Shirt", Category = "cloths" }
- };
- public IEnumerable<Item> GetAllItems()
- {
- return items;
- }
- public Item GetItemById(int id)
- {
- var item = items.FirstOrDefault((i) => i.Id == id);
- if (item == null)
- {
- throw new HttpResponseException(HttpStatusCode.NotFound);
- }
- return item;
- }
- public IEnumerable<Item> GetItemsByCategory(string category)
- {
- return items.Where(i => string.Equals(i.Category, category,
- StringComparison.OrdinalIgnoreCase));
- }
- }
- }
Step 7
Now we Host our Web API.
Open the "Program.cs" file and add this code into this file:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web.Http;
- using System.Web.Http.SelfHost;
- namespace Hosting
- {
- class Program
- {
- static void Main(string[] args)
- {
- var config = new HttpSelfHostConfiguration("http://localhost:8080");
- config.Routes.MapHttpRoute(
- "API Default", "api/{controller}/{id}",
- new { id = RouteParameter.Optional });
- using (HttpSelfHostServer server = new HttpSelfHostServer(config))
- {
- server.OpenAsync().Wait();
- Console.WriteLine("Press Enter to quit.");
- Console.ReadLine();
- }
- }
- }
- }
Step 8
Add a new project in this application using the following:
- In the "Solution Explorer".
- Right-click on project then select "Add" -> "New Project"
- Change the name to "Client".
Step 9
Install the "Microsoft ASP.NET Web API Client Library" using the following:
- Go to the "Tools" menu then select "Extension and Updates".
- In the "Extension and Updates" dialog box select "Online".
- In the search box type "Microsoft.AspNet.WebApi.Client".
- Select the "Microsoft ASP.NET Web API library" and install it.
Step 10
Add the reference of the client to the "Hosting" project using the following:
- In the "Solution Explorer" right-click on the "Client" project.
- Select "Add reference".
- Open a "Reference" dialog box.
- Select the solution and choose "Projects".
- Click on the "Ok" button.
Step 11
Open the "Program.cs" file in the "Client" project.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Net.Http;
- namespace Client
- {
- class Program
- {
- static HttpClient client = new HttpClient();
- static void Main(string[] args)
- {
- client.BaseAddress = new Uri("http://localhost:8080");
- ListAllItems();
- ListItem(1);
- ListItems("fruit");
- Console.WriteLine("Press Enter to quit.");
- Console.ReadLine();
- }
- static void ListAllItems()
- {
- HttpResponseMessage resp = client.GetAsync("api/items").Result;
-
- var items = resp.Content.ReadAsAsync<IEnumerable<Hosting.Item>>().Result;
- foreach (var i in items)
- {
- Console.WriteLine("{0} {1} {2}", i.Id, i.Name, i.Category);
- }
- }
- static void ListItem(int id)
- {
- var resp = client.GetAsync(string.Format("api/products/{0}", id)).Result;
-
- var item = resp.Content.ReadAsAsync<Hosting.Item>().Result;
- Console.WriteLine("ID {0}: {1}", id, item.Name);
- }
- static void ListItems(string category)
- {
- Console.WriteLine("items in '{0}':", category);
- string query = string.Format("api/items?category={0}", category);
- var resp = client.GetAsync(query).Result;
- resp.EnsureSuccessStatusCode();
- var items = resp.Content.ReadAsAsync<IEnumerable<Hosting.Item>>().Result;
- foreach (var item in items)
- {
- Console.WriteLine(item.Name);
- }
- }
- }
- }
Step 12
Now execute the application.
- In the "Solution Explorer" right-click on the "Hosting" Project.
- And select "set as Start up project".
- Press F5 for execution.
Step 13
Debug the project "Hosting" using the following:
- In the Solution Explorer" right-click on the project "Client".
- Select "Debug"-> "Start new instance".
Output