Introduction
Before reading this article, I highly recommend reading the previous parts:
In this article, we will learn about the Self-Host ASP.NET Web API. Without IIS we are able to run our Web API using the Web API self-hosting capabilities.
To make the run a self-hosted ASP.NET Web API, we need to create an instance of a HttpSelfHostConfiguration and pass it into an instance of HttpSelfHostServer, that will create the WCF channel stack responsible for the HTTP interaction of our Web API service.
The following is a code sample to show the Self-Hosting Web API:
- var address = "http://localhost:1234";
- var congig = new HttpSelfHostConfiguration(address);
- congig.MapHttpAttributeRoutes();
- server.OpenAsync().Wait();
- Console.WriteLine("server running at {0}. Press any key to exit", address);
- Console.ReadLine();
-
The Web API is self-hosting, using a Windows Communication Foundation, that is available on:
NuGet: Install-Package Microsoft.AspNet.WebApi.SelfHost
As we know that the first version of the Web API also supports the self-hosted mode that is on HttpListener and allows us to run Web API services outside of ASP.NET. We can turn any .NET application into a Web API server, as long as it meets the following requirements:
- Assigns a specific port, meaning that the URL and port had been reserved for the application with the relevant netsh command. or administrator privileges.
- Now it would will be able to reference and utilize the WCF components that the Web API self-host is built on, such as System.ServiceModel.
ASP.NET Web API 2 self-hosts using the WCF channel stack layer for getting request messages from the underlying HTTP infrastructure. HttpSelfHostServer sets up an HttpBinding that is configured using the data provided through HttpSelfHostConfiguration, then the HttpBinding is used to configure a WCF message channel stack that is responsible for the communication with the operating system's networking stack. This is the common logic behind the self host.
To run the application using the administrator's mode is the best idea, and if not, then use the netsh tool to reserve a URL for a specific user account.
This is the way we can add a URL and remove a URL.
- Add a URL:
netsh http add urlacl url=http://+:1234/ user=domian\username
- Remove a URL:
netsh http delete urlacl url=http://+:1234/
At application startup, HttpListener tries to register a URL to be able to receive HTTP requests.
Now let's start to develop a slef hosted application using the console based template.
Prerequisites
The following things are needed when developing a Web API 2 application for the Self-Host Web API.
Visual Studio 2013
Getting Started
In this section we will follow some important procedures and these are:
- Create Console Application
- Add a class file for student
- Add a class for ApiController.
Step 1
Open the Visual Studio 2013 and click New Project.
Step 2
Select the Console based application and provide a nice name for the project.
Step 3
Add a class named student and use a property.
- using System.ComponentModel.DataAnnotations;
- namespace SelfHosting
- {
- public class Student
- {
- [Required]
- public int Id { get; set; }
- public string Name { get; set; }
-
- }
- }
Step 4
The following is a procedure to install the self-host namespace using the NuGet Package Manager.
- Right-click on the Project Name and choose "Manage NuGet Packeges..." as you see in the the following image.
- Search "selfhost" packeges and we will see a list of selfHost packages. Select Microsoft ASP.NET Web API 2.2 Self Host.
- Click to Install.
- After installation we will get a prompt for " I Accept".
Then we will see the complete installation.
Step 5
Add a Controller class that is inherits from the ApiController class using the System.Web.Http namespace.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web.Http;
-
- namespace SelfHosting
- {
- public class StudentController: ApiController
- {
- private static List<Student> stud = new List<Student>{
- new Student{Id=1, Name="Rajeev"},
- new Student{Id=2, Name="Ranjan"}
- };
- [Route("student")]
- public IEnumerable<Student> Get()
- {
- return stud;
- }
- [Route("student/{id:int}",Name="StudentById")]
- public Student GetById(int id)
- {
- var studen = stud.FirstOrDefault(x => x.Id == id);
- if (studen == null) throw new HttpResponseException(HttpStatusCode.NotFound);
- return studen;
- }
- [Route("student")]
- public IHttpActionResult Post(Student s)
- {
- stud.Add(s);
- return CreatedAtRoute("StudentById", new { id = s.Id }, s);
- }
-
- }
- }
Step 5
In this section we will simply start the server and get the data (student records) in JSON format using the web API controller and without IIS.
- using System;
- using System.Net.Http;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web.Http;
- using System.Web.Http.SelfHost;
- namespace SelfHosting
- {
- class Program
- {
-
- static void Main(string[] args)
- {
- var address = "http://localhost:1234";
- var congig = new HttpSelfHostConfiguration(address);
- congig.MapHttpAttributeRoutes();
- using (var server = new HttpSelfHostServer(congig))
- {
-
- server.OpenAsync().Wait();
- Console.WriteLine("server running at {0}. Press any key to exit", address);
- var client = new HttpClient()
- {
- BaseAddress = new Uri(address)
- };
- var students = client.GetAsync("student").Result;
- Console.WriteLine(students.Content.ReadAsStringAsync().Result);
- var newStudent = new Student { Id = 3, Name = "Nisa" };
- var response = client.PostAsJsonAsync("student", newStudent).Result;
-
- if (response.IsSuccessStatusCode)
- {
- var student3 = client.GetAsync("student/3").Result;
- Console.WriteLine(student3.Content.ReadAsStringAsync().Result);
- }
- Console.ReadLine();
- }
-
- }
- }
- }
Output
Further Reading
Getting Started with ASP.NET Web API 2 : Day 11