How to Self Host a Web API Application


In this article we will see how to how to Self Host a Web API Application. We can host a WEB API in IIS/Windows applications or even a console based application. In this article we will self host the Web API application in its own host process in a console based application.

In this article we will see how to how to Self Host a Web API Application.

We can host a WEB API in IIS/Windows applications or even a console based application. In this article we will self host the Web API application in its own host process.

Step1:
Launch Visual Studio 2012 -> File -> New -> Project -> On the Left Side of open dialog box Select Installed ->Templates -> Visual C# -> Console Application-> Name : "SelfHostWebAPIDemo".
consoleselfhostserver
Step2:
Since ours is a console application, We need to add Web API assemblies using NuGet Package Manager. If you are new to creating Web API, First you need to download and install it using below process.
Go To Tools -> Extenstions and Updates -> Select Online on Left hand side -> type "nuget" in the search box -> Select the NuGet Package Manager -> click Download -> Install.
extupd
This install Nuget Package Manager.
Step3:
Right click the project in solution explorer -> click Manage Nuget Packages -> In the Manage NuGet Packages window -> in the search box type self host -> This lists the self host packages -> select ASP.NET Web API Self Host -> click on Install -> Accept the License Agreement -> Click on close.
managenuget
Step4:Add a Model to the project
Add a class "Emp" to the project as shown below:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SelfHostWebAPIDemo
{
public class Emp
{
public int EmpId { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
}
}

Step5:Add a Controller to the project
Add a class "EmpController" to the project and add the "using System.Web.Http;
" and "using System.Net" at the top of the class. Derive this class from the ApiController class as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace SelfHostWebAPIDemo
{
public class EmpController : ApiController
{
List lstEmp = new List();
Emp[] Emps = new Emp[]
{
new Emp { EmpId = 1, Name = "Srihita", Salary = 10000,Gender="Male" },
new Emp { EmpId = 2, Name = "Krishna", Salary = 25000,Gender="Male" },
new Emp { EmpId = 3, Name = "John", Salary = 48000,Gender="Female" }
};

public IEnumerable GetAllEmps()
{
return Emps;
}

public Emp GetEmpById(int id)
{
var Emp = Emps.FirstOrDefault((e) => e.EmpId == id);
if (Emp == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return Emp;
}

public IEnumerable GetEmpsByGender(string gender)
{
return Emps.Where(s => string.Equals(s.Gender, gender,
StringComparison.OrdinalIgnoreCase));
}

}
}

In the above code we have written below three methods:
GetAllEmps: returns all the Employee details.
GetEmpById: returns a specific Employee with an id passed as parameter to this class.
GetEmpsByGender: Returns list of Employees with matching Gender same as the parameter passed to this method.

Step 6:Host the Web API in the console application
In the Program class add the following using statements

using System.Web.Http;
using System.Web.Http.SelfHost;

Add the following code to the Program class.

static void Main(string[] args)
{
var config = new HttpSelfHostConfiguration("http://localhost:8999");
//Maps the specified route template(api/controller/id)
config.Routes.MapHttpRoute("default", "api/{controller}/{id}", new { id = RouteParameter.Optional });
var server = new HttpSelfHostServer(config);
var task = server.OpenAsync();
task.Wait();
Console.WriteLine("server is up and running");
//to keep the console application up and available
Console.ReadLine();

}

Step7: Creating a console application which will be the client application to call the Web API
newclientproj
In the Solution Explorer ->Right click the solution -> Add New Project -> Visual C# -> Console Application -> Name:ClientApplication -. OK
clientapp
Step 8:Now we need to add "ASP.NET Web API Client Libraries" to the client project using NuGet Package Manager.
Right Click ClientApplication project in the Solution Explorer -> Select Manage NuGet Packages -> Select Online on the left and on the right type "Microsoft.AspNet.WebApi.Client" in the search box -> Select the Microsoft ASP.NET Web API Client Libraries package and click Install ->Accept License Agreement -> Close
clientmanagenuget
nugetclient
Step 9:Add reference to the SelfHost Web API project in the Client Application
In Solution Explorer->Right-click the ClientApplication project-> Add Reference->
In the Reference Manager dialog, under Solution, select Projects.
Select the SelfHostWebAPIDemo project -> Click OK.
serverref
Step 10:Calling Web API methods
Add using System.Net.Http; at the top of the Program.cs class of the Client Application. Create a HttpClient instance and add code to list all employees, list an employee by ID, and list employees by gender as shown below:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;

namespace ClientApplication
{
class Program
{
static HttpClient client = new HttpClient();
static void Main(string[] args)
{
//connect to the server hosted on the uri mentioned in the Uri instance
client.BaseAddress = new Uri("http://localhost:8999");

GetAllEmployees();
GetEmployee(1);
GetEmployees("Female");

Console.WriteLine("Press Enter to quit.");
Console.ReadLine();

}
//Gets all the employee details and displays on the console window.
static void GetAllEmployees()
{
HttpResponseMessage resp = client.GetAsync("api/Emp").Result;
resp.EnsureSuccessStatusCode();

var employees = resp.Content.ReadAsAsync>().Result;
foreach (var e in employees)
{
Console.WriteLine("{0} {1} {2} {3}", e.EmpId, e.Name, e.Salary, e.Gender);
}
}

//Gets employee details with a specific employee id and displays on the console window.
static void GetEmployee(int id)
{
var resp = client.GetAsync(string.Format("api/Emp/{0}", id)).Result;
resp.EnsureSuccessStatusCode();

var emp = resp.Content.ReadAsAsync().Result;
Console.WriteLine("ID : {0} with Name : {1}", id, emp.Name);
}

//Gets employees with gender matching the parameter value and displays on the console window.
static void GetEmployees(string gender)
{
Console.WriteLine("{0} employee", gender);

string query = string.Format("api/emp?gender={0}", gender);

var resp = client.GetAsync(query).Result;
resp.EnsureSuccessStatusCode();

var emps = resp.Content.ReadAsAsync>().Result;
foreach (var emp in emps)
{
Console.WriteLine(emp.Name);
}
}
}
}


Step 11:Run the Web-API Server application
Make the "SelfHostWebAPIDemo" project as the start up project and Press Ctrl +F5 to run the server. This makes our web api up and running. The output is as shown below:
serveravailable
Step 12:Run the Client Application
Right click the "ClientApplication" project -> debug -> start new instance. Now the application will connect to the web-api server applications and gets the data and displays the output as shown below:
cilentoutput

Please make sure you run Visual Studio as an administrator.


Article by Vaishali Jain
Miss. Jain Microsoft Certified Technology Specialist in .Net(Windows and Web Based application development)

Follow Vaishali Jain or read 127 articles authored by Vaishali Jain

Comments

Author: Umesh Bhosale15 Apr 2014 Member Level: Silver   Points : 0

Nice Article.

Author: Umesh Bhosale21 Apr 2014 Member Level: Silver   Points : 0

Hi Priya
I am developing application with WEB Api with contains Nuget Packages can you please explain how can i host this application into IIS.

Thanks
Umesh Bhosale

Author: Vaishali Jain26 Apr 2014 Member Level: Gold   Points : 0

Sorry for late response Umesh. Once you develop your web application host it in IIS this in turn will host Web API in IIS.

Author: Laxmikant07 Nov 2014 Member Level: Gold   Points : 0

if you have separate service assembly developed with ASP.NET Web API and host it in IIS check
http://dotnetmentors.com/web-api/host-asp-net-web-api-in-iis-using-visual-studio-publish.aspx



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: