Hosting Web API in Windows service

Running your api as Windows services can have multiple advantages, especially when working on bigger projects. This allows for multiple (services to run in isolation and gives fine grained control over your system components.

ASP.NET Web API ships with self-hosting feature that allows to run HTTP service outside of IIS. This can be easily used in Windows services. In this blog post I am going to show how to host Web API service inside of Windows service, using both Windows Service Visual Studio project template andTopshelflibrary.

Please note that I am using Visual Studio 2012 RC and Web API nightly build NuGet packages in the following examples.

Project setup

Start off by creating a new Windows service project.

Now, add reference to ASP.NET Web API. I‘m taking advantage of NuGet and nightly build packages, but Web API RC pieces should work as well. If you are looking for instructions, check this blog post by Henrik F Nielsen.

Implementation

The implementation is straightforward, we just need to create HttpSelfHostServer instance and call OpenAsync when the service starts. 
For the sake of simplicity I‘ve skipped logging and xml configuration (to configure service address).

public partial class HttpApiService : ServiceBase
{
    private HttpSelfHostServer _server;
    private readonly HttpSelfHostConfiguration _config;
    public const string ServiceAddress = "http://localhost:2345";

    public HttpApiService()
    {
        InitializeComponent();

        _config = new HttpSelfHostConfiguration(ServiceAddress);
        _config.Routes.MapHttpRoute("DefaultApi",
            "api/{controller}/{id}",
            new {id = RouteParameter.Optional});
    }

    protected override void OnStart(string[] args)
    {
        _server = new HttpSelfHostServer(_config);
        _server.OpenAsync();
    }

    protected override void OnStop()
    {
        _server.CloseAsync().Wait();
        _server.Dispose();
    }
}
public class ApiServiceController : ApiController
{
    public string Get()
    {
        return "Hello from windows service!";
    }
}

Installation

The easiest way to install and test your service is using installutil.exe utility. Open your visual command prompt as administrator and go to bin\Debug folder of your service. To install it run:

installutil Piotr.ApiWindowsService.Service.exe

To uninstall:

installutil /u Piotr.ApiWindowsService.Service.exe

You may want to follow these instructions and add service installer along with a separate setup project to install your service. This would enable you to

Alternative approach - using Topshelf

Topshelfis a project aimed to simplify development and management of windows services. You can get it throught NuGet or download it on project‘s website.

Let‘s try to use it to host web api http server.

Create a new console applicaton and add a class library project to contain your service.

public class HttpApiService
{
    private readonly HttpSelfHostServer _server;
    private readonly HttpSelfHostConfiguration _config;
    private const string EventSource = "HttpApiService";

    public HttpApiService(Uri address)
    {
        if (!EventLog.SourceExists(EventSource))
        {
            EventLog.CreateEventSource(EventSource, "Application");
        }
        EventLog.WriteEntry(EventSource,
            String.Format("Creating server at {0}",
            address.ToString()));
        _config = new HttpSelfHostConfiguration(address);
        _config.Routes.MapHttpRoute("DefaultApi",
            "api/{controller}/{id}",
            new { id = RouteParameter.Optional }
        );
        _server = new HttpSelfHostServer(_config);
    }

    public void Start()
    {
        EventLog.WriteEntry(EventSource, "Opening HttpApiService server.");
        _server.OpenAsync();
    }

    public void Stop()
    {
        _server.CloseAsync().Wait();
        _server.Dispose();
    }
}

Please note that the service class is a plain object and does not extend any special classes. Topshelf uses logical services which makes them easily reusable outside of windows service context. I would say this is one of advantages over ‘classic‘ approach presented earlier.

In your console app project you need to include hosting code. Topshelf gives you some flexibility on how you can actually host your service(s) (eg.shelving) , which is nicely decoupled from service implementation details.

static void Main(string[] args)
{
    HostFactory.Run(x =>
    {
        x.Service<HttpApiService>(s =>
        {
            s.SetServiceName("Piotr.WebApiTopShelfService");
            s.ConstructUsing(name => new HttpApiService(new Uri("http://localhost:1234")));
            s.WhenStarted(tc => tc.Start());
            s.WhenStopped(tc => tc.Stop());
        });
        x.RunAsLocalSystem();
        x.StartManually();
        x.SetDescription("Sample Web API Windows service");
        x.SetDisplayName("Piotr.WebApiTopShelfService");
        x.SetServiceName("Piotr.WebApiTopShelfService");
    });
}

This is basically all you need to do to implement a simple Web API service using Topshelf. To install it issue following command as administrator:

Piotr.WebApiTopShelfService.exe install

To uninstall:

Piotr.WebApiTopShelfService.exe uninstall

Once you start your service,

you should be able to make HTTP requests to your self hosted Web API server.

That‘s it! ASP.NET Web API self hosting features enabled us to use Windows service as a hosting process with minimal effort.

时间: 2024-10-21 09:13:09

Hosting Web API in Windows service的相关文章

WCF - Windows Service Hosting

WCF - Windows Service Hosting The operation of Windows service hosting is a simple one. Given below are the steps with requisite coding and screenshots that explain the process in an easy way. 在windows服务上托管wcf是一个简单的操作. Step-1: Now let’s create a WCF

ASP.NET Web API系列教程(目录)(转)

注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP.NET Web API.这是一个用来在.NET平台上建立HTTP服务的Web API框架,是微软的又一项令人振奋的技术.目前,国内对此关注的人似乎还不多,有关ASP.NET Web API的文章也不多见.为此,本人打算对微软ASP.NET Web API官方网站上的一些教程进行翻译,以期让更多的国人了解.学习和使用这项ASP.NET Web API. ASP.NET Web API系列教程目录 Introduction:Wha

ASP.NET Web API系列教程目录

ASP.NET Web API系列教程目录 Introduction:What's This New Web API?引子:新的Web API是什么? Chapter 1: Getting Started with ASP.NET Web API第1章 ASP.NET Web API入门 Your First Web API (C#)第一个Web API(C#) Deep Dive into Web API深入探讨Web API(这是一个视频教程,本翻译系列略) Pro ASP.NET Web

ASP.NET Web API 应用教程(一) ——数据流使用

相信已经有很多文章来介绍ASP.Net Web API 技术,本系列文章主要介绍如何使用数据流,HTTPS,以及可扩展的Web API 方面的技术,系列文章主要有三篇内容. 主要内容如下: I  数据流 II 使用HTTPS III 可扩展的Web API 文档 项目环境要求 VS 2012(SP4)及以上, .Net 框架4.5.1 Nuget包,可在packages.config 文件中查寻 本文涉及的知识点 ActionFilter AuthorizationFilter Delegate

web service, wcf, wcf rest, web api之间的区别

在.NET Framework中,有很多种技术可以创建基于http协议的服务,譬如说web service, wcf,wcf rest和web api等等.网上有很多的文章教我们如何开发.使用这几种技术,但是没有说明他们之间的关系,经过一段时间的查阅资料,现将我的理解整理如下. web service: 基于SOAP,仅仅支持http协议. 数据传输格式是xml. 只能部署在iis上面. wcf: 基于soap,支持多种传输协议,如http,https,tcp,msmq和命名管道等等. 数据传输

ASP.NET Web API: 宿主(Hosting)

参考页面: http://www.yuanjiaocheng.net/webapi/test-webapi.html http://www.yuanjiaocheng.net/webapi/web-api-controller.html http://www.yuanjiaocheng.net/webapi/config-webapi.html http://www.yuanjiaocheng.net/webapi/web-api-route.html http://www.yuanjiaoch

不写画面的网页程序设计,Web API、Web Service、WCF Service

客户有一个系统,经常要连上我方,查询数据 以前的作法是给对方一个账号,让他可以连上我们的DB来查询. 所以,早期的同仁,真的给他们DB链接字符串 客户的Windows程序.网站就真的靠这么危险的方式,连上我们公司的DB. 但怎么想都觉得危险,而且...... 如果对方SQL指令乱下,把效能搞得更烂,岂不是惨兮兮? 如果对方不小心,配置文件被偷走,看到我方DB Connection String怎么办? 几年前的 Internet还没有那么大的带宽,所以还得种种限制,避免他们一次查询太多数据 我接

WCF、Web API、WCF REST、Web Service比较

原文地址:http://www.dotnet-tricks.com/Tutorial/webapi/JI2X050413-Difference-between-WCF-and-Web-API-and-WCF-REST-and-Web-Service.html WCF 1.基于Soap协议,以XML形式返回. 2.是Web Service的进化 支持多种协议:TCP,HTTP,HTTPS,命名管道,消息队列. 3.缺点:冗长的大量配置. 4.不开源,但是可以被懂xml的定制. 5.可以部署在应用.

Web API、WCF和Web Service的区别

[转载] Web Service 1.它是基于SOAP协议的,数据格式是XML 2.只支持HTTP协议 3.它不是开源的,但可以被任意一个了解XML的人使用 4.它只能部署在IIS上 WCF 1.这个也是基于SOAP的,数据格式是XML 2.这个是Web Service(ASMX)的进化版,可以支持各种各样的协议,像TCP,HTTP,HTTPS,Named Pipes, MSMQ. 3.WCF的主要问题是,它配置起来特别的繁琐 4.它不是开源的,但可以被任意一个了解XML的人使用 5.它可以部署