Dataworks Blog

    SELF HOSTING A WEB API SERVICE

  • Self Hosting a Web API Service

    Web API

    ASP.Net Web API is a relatively new set of technologies from Microsoft for creating web services. You can find more information on it here http://www.asp.net/web-api

    Self-hosting

    Normally a Web API Service would be hosted in IIS but for when you can’t or don’t want to use IIS to host your service, the Web API libraries to provide the mechanisms necessary to allow you to create your own hosts. 

    Example

    Create a solution with 2 projects. One project will be our server and the other a client. We need to add the Web API libraries to our server project. The quickest way to do this is to use NuGet. Run the following NuGet commands for the server project

    Install-Package Microsoft.AspNet.WebApi

     and

    Install-Package Microsoft.AspNet.WebApi.SelfHost

    Our client will also need some libraries to connect to a web API service. Run the NuGet command “Install-Package Microsoft.Net.Http” for the client project

    In the server project add the following classes

    usingSystem;
    usingSystem.Web.Http;
    usingSystem.Net;
    usingSystem.Net.Http;
    
    namespaceWebAPISelfHostingDemo
    {
        public class DemoController : ApiController
        {
            public string Get(string message)
            {
                Console.WriteLine(String.Format("Received from client: {0}", message));
                return "Hi There. Thanks for your message";
            }
        }
    }
    
    usingSystem;
    usingSystem.Web.Http;
    usingSystem.Web.Http.SelfHost;
    namespaceWebAPISelfHostingDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                string baseAddress = "http://localhost:8085/";
                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);
                config.Routes.MapHttpRoute(name: "API Default",
    routeTemplate: "api/{controller}/{message}",
                    defaults: new { id = RouteParameter.Optional }
                );
                using (HttpSelfHostServer server = new HttpSelfHostServer(config))
                {
                    server.OpenAsync().Wait();
                    Console.WriteLine("Listening on " + baseAddress);
                    Console.WriteLine("Press enter when finished.");
                    Console.ReadLine();
                }
            }
        }
    }
    

    Create the Client

    usingSystem;
    usingSystem.Net.Http;
    
    namespaceWebAPIClient
    {
        class Program
        {
            static void Main(string[] args)
            {
                HttpClient client = new HttpClient();
                Console.WriteLine("Client Running");
                Console.WriteLine("Press enter to get the servers message.");
                string message = Console.ReadLine();
                client.GetStringAsync("http://localhost:8085/api/Demo/" + message).ContinueWith(
                    getTask =>
                        {
                            Console.WriteLine(String.Format("Received: {0}", getTask.Result));
                        });
                Console.WriteLine("Press enter to quit.");
                Console.ReadLine();
            }
        }
    }
    

    One further thing that may need to be done is to give the current user rights to run a sever on the port . There are a few ways to do this. The simplest is using the Netsh tool. You can run the following from and administrator level command prompt

    netsh http add urlacl url=http://+:8085/ user=machine\user
    

    Where “machine\user” is the user account that will run the server program.

    Once you’re finished you can release the port with

    netsh http deleteurlacl url=http://+:8085/

    When you run the project you will see 2 command prompts. If you type a message in the client window and press enter, the message will appear in the server window and you will see the server’s response in the client window.

  • Back to Blogs