Learn Self Host of a Web API(C#) Part 1

Rama Sagar
Posted by in ASP.NET Web API category on for Beginner level | Points: 250 | Views : 4113 red flag

Self hosting means running our ASP.Net Web API project in our own Web Server rather than via IIS. Here we are not building a complete Http Web server either. We’re simply using functionality.

Introduction


This article shows the walk through of self hosting a Web API...

Here we will see how to host a web API inside a console application.


  • Step 1 : Create a New Project  Open visual studio 2013 in Admin mode -> click on File -> New Project ->select Console Application





  • Step 2 : Install  Microsoft.AspNet.WebApi.SelfHost through Packager Manager console as shown below
         Click on Tools--->Select Library Package Manager-->Package Manager Console and Type the following command

                                          


                 Install-Package Microsoft.AspNet.WebApi.SelfHost



  • Step 3 : Now lets create Model and Controller
         We will use the same Model and Controller from this article

namespace SampleSelfHost
{
    public class Student
    {

        public int Id { get; set; }
        public string Name { get; set; }
        public string Standard { get; set; }
        public decimal Marks { get; set; }

    }
}

Now add a public class named StudentsController . Derive this class from System.Web.Http.ApiController.


using SampleSelfHost;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;

namespace SelfHost
{
    public class StudentsController : ApiController
    {
        Student[] students = new Student[]  
        {  
            new Student { Id = 1, Name = "Sagar", Standard = "seventh", Marks = 60 }, 
            new Student { Id = 2, Name = "Sachin", Standard = "seventh", Marks = 70 }, 
            new Student { Id = 3, Name = "Dravid", Standard = "seventh", Marks = 90 },
            new Student { Id = 4, Name = "Ramesh", Standard = "seventh", Marks = 90 }, 
            new Student { Id = 5, Name = "Ganguly", Standard = "seventh", Marks = 90 }, 
            new Student { Id = 6, Name = "Rahul", Standard = "seventh", Marks = 90 }, 
        };

        public IEnumerable<Student> GetAllStudents()
        {
            return students;
        }

        public Student GetStudentById(int id)
        {
            var Student = students.FirstOrDefault((p) => p.Id == id);
            if (Student == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return Student;
        }

        public IEnumerable<Student> GetStudentsByStandard(string standard)
        {
            return students.Where(p => string.Equals(p.Standard, standard,
                    StringComparison.OrdinalIgnoreCase));
        }
    }
}

 
  Now Lets Host a web API

 Open Program.cs class file from the solution explorer



Add the Following Implementation 

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

namespace SampleSelfHost
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8080");

            //To determine which action to invoke, the framework uses a routing table. The Visual Studio project template for Web API creates a default route
            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();

                Console.WriteLine("Listening for HTTP requests.");
                Console.WriteLine("(Please Run the ClientApp project to send requests).");
                Console.WriteLine();
                Console.WriteLine("You can hit Enter to quit.");
                Console.ReadLine();
            }
        }
    }
}

Now run the Application and make sure that Visual studio 2013 is opened in Administrator Mode otherwise you might get an error "HTTP could not register URL http://+:8080/"

 The following output should appear



Conclusion

In this article we have seen how to host the web API. In the next part of this article we will see how to call Web API from a Client Application (C#)

Reference

http://www.matlus.com/self-host-asp-net-web-api/

Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)