Host WebApi2 in Windows Service with HTTPS/SSL (Part1)

Services
4 minutes to read read

With the introduction of OWIN  and self hosting, microsoft has really opened a lot of possible doors for developers and application users. This post is targetted to have an OWIN application hosted in Windows Service. Also we would be configuring the SSL for the Site.

Source code can be accessed at: GitHub

Creating a Windows Services Project

This is pretty straightforward. In visual Studio, Create new project and select Windows Service as project. This will add a project with default Service “Service1”. Rename to whatever the name expected.

Add OwinSelfHost and WebApi2

In the Tools-> Nuget package Manager -> PM console type in the following command to get the WebApi and self host packages referenced.

Install-Package Microsoft.Aspnet.WebApi.OwinSelfHost

This will install and reference all the required packages and dependencies. Also we need one more package to debug and use some functions like welcome package. For this import the  Microsoft.Owin.Diagnostics using PM Console.

Install-Package Microsoft.Owin.Diagnostics

Also, to Enable Cross Origing Resource Sharing, we need to import the following package:

Install-Package Microsoft.Owin.Cors

At this point the we are Good to Start.

Owin Startup File

We use the following Owin Startup File. The file has simple functions with just setting the base parameters to get the WebApi and Owin up and running. Please note we are using the port number 8099. This can be changed to read from config file.

    /// <summary>
    /// Owin Startup Class
    /// </summary>
    public class OwinStartup
    {
        /// <summary>
        /// Configuration Method for Owin
        /// </summary>
        public void Configuration(IAppBuilder appBuilder)
        {
            //Set the Welcome page to test if Owin is hoosted properly
            appBuilder.UseWelcomePage("/welcome.html");
            appBuilder.UseErrorPage(new ErrorPageOptions() { ShowExceptionDetails = true });

            HttpConfiguration config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                name: "defaultApiRoute",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            //Maps Http routes based on attributes
            config.MapHttpAttributeRoutes();

            //Enable WebApi
            appBuilder.UseWebApi(config);
            appBuilder.UseCors(CorsOptions.AllowAll);
        }
    }

Update Service Methods to Start and Stop the hosted Application

We use the standard Microsoft way of starting and stopping the Application. The simple changes are highlighted below

 public partial class OwinStartupService : ServiceBase
    {
        private IDisposable server;
        /// <summary>
        /// Constructor
        /// </summary>
        public OwinStartupService()
        {
            InitializeComponent();
        }

        /// <summary>
        /// On Service Start
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            string baseAddress = "http://localhost:8099/";
            server = WebApp.Start<OwinStartup>(baseAddress);
        }

        /// <summary>
        /// On Service Stop
        /// </summary>
        protected override void OnStop()
        {
            server?.Dispose();
        }
    }

Add Project installer

For installing the service, we need to add project installer to our service. Without going in more details which are always available on MSDN here.

Open the designer view on Service and Right click and select “Add Installer”.

Add Service Installer

Add Service Installer

This will add a installer class by the name of Project installer. It shall have two components as below:

Service Process Installer

Service Process Installer

Now we need to modify the Security Context of the service to run as Local System. Click on the ServiceProcessInstaller and then select properties. Then change Account to Local System.

Service Properties

Comple the Solution. it should Compile Ok….

Installing and Uninstalling the Service

Open the Visual Studio Command line tools. Navigate to the bin folder of your exe and execute the following command using installUtil Command.

installutil OwinSslWindowsService.exe

This would produce a similar output as below indicating success.

Service Installation

Service Installation

 

Go to Service and you should your service listed there

Services

Services

 

Start the service and Open Web browser. Then try to access the port number specified (8099) in our case /welcome.html as path. This should show Owin startup page indicating that the application is successfully hosted.

Services Hosted Successfully

Services Hosted Successfully

 

Please follow part 2 of this post for adding SSL (HTTPS) to our hosted windows service.

 

Leave a Reply

Your email address will not be published. Required fields are marked *