Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example self-hosting a Web API endpoint in a Windows Service using TopShelf (https://topshelf.readthedocs.org) and TopShelf.Owin package.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="Port" value="1337"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.2" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.2" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Owin" version="5.2.2" targetFramework="net452" />
<package id="Microsoft.Owin" version="3.0.0" targetFramework="net452" />
<package id="Microsoft.Owin.Host.HttpListener" version="3.0.1" targetFramework="net452" />
<package id="Microsoft.Owin.Hosting" version="3.0.0" targetFramework="net452" />
<package id="Newtonsoft.Json" version="6.0.4" targetFramework="net452" />
<package id="Owin" version="1.0" targetFramework="net452" />
<package id="Topshelf" version="3.1.4" targetFramework="net452" />
<package id="Topshelf.Owin" version="1.3.12.0" targetFramework="net452" />
</packages>
using System;
using System.Net;
using System.Web.Http;
using Topshelf;
using TopShelf.Owin;
namespace HelloService
{
class Program
{
static void Main(string[] args)
{
HostFactory.Run(c =>
{
c.RunAsNetworkService();
c.Service<ProxyController>(s =>
{
s.ConstructUsing(name => new ProxyController());
s.WhenStarted((service) => service.Start());
s.WhenStopped((service) => service.Stop());
s.OwinEndpoint(app =>
{
app.Domain = "localhost";
app.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Port"]);
/* Windows Authentication
app.ConfigureAppBuilder(ab =>
{
HttpListener listener = (HttpListener)ab.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
});*/
app.ConfigureHttp(config =>
{
// Attribute routing
config.MapHttpAttributeRoutes();
});
});
});
});
}
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
namespace HelloService
{
public class ProxyController : ApiController
{
[Route("hello")]
[HttpGet]
public string Hello()
{
return "Hello";
}
public bool Stop()
{
return true;
}
public bool Start()
{
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.