Yoav Lavi
Yoav Lavi

Reputation: 375

Creating an API endpoint in a .NET Windows Service

I have an ASP.NET project and a .NET Windows service running on the same machine, and I want them to communicate (currently only ASP.NET => Service one way).

The most convenient way to do this (IMO) would be a REST / other API endpoint in the service which the ASP.NET project would call (since ASP.NET works with APIs anyway and they can be protected etc.). The problem is that I can't seem to find a way to do this in a Windows service. Is there a native method / library to support this?

Using .NET Framework 4.5.2 in both projects.

Upvotes: 16

Views: 27619

Answers (1)

Stefan
Stefan

Reputation: 17648

.NET Core ERA and beyond

A lot has changed since I wrote this post. .NET (dotnet) Core has become more famous - and we're even already past that; welcome .NET 5.

Using ASP.NET core makes the task addressed in the question much easier and is the way to go in a new setup or project.

Just create a new project choosing the ASP.NET Core template. It contains templates for API only, MVC, SPA - etc. (or if you want to include pages optionally go for Blazor) and have a look at one of the tutorials mentioned below.

enter image description here

Documentation for a Windows service can be found here. (host-and-deploy/windows-service)

If you are using linux as host OS - there is an excellent article on how to accomplish the setup: by Niels Swimberghe


Legacy

As for ASP.NET Core 2.2 check out this article


Original answer - pre .NET Core (-ish).

There is a library available at nuget:

https://www.nuget.org/packages/Microsoft.AspNet.WebApi.OwinSelfHost

There is an article on how to use it here. It's an console app, but easily converted to a windows service.

class Program
{
    static void Main(string[] args)
    {
        using (WebApp.Start<Startup>("http://localhost:8080"))
        {
            Console.WriteLine("Web Server is running.");
            Console.WriteLine("Press any key to quit.");
            Console.ReadLine();
        }
    }
}

You will find you will have all common API features, (i.e. controllers, routes, actionfilters) available.

Upvotes: 16

Related Questions