DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Deploy an ASP.NET Core Application in the IBM Cloud Code Engine
  • Alexa Skill With .NET Core
  • GDPR Compliance With .NET: Securing Data the Right Way

Trending

  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Why High-Performance AI/ML Is Essential in Modern Cybersecurity
  • A Deep Dive Into Firmware Over the Air for IoT Devices
  1. DZone
  2. Coding
  3. Frameworks
  4. Running an ASP.NET Core Application as a Windows Service

Running an ASP.NET Core Application as a Windows Service

We can now run ASP.NET Core applications as Windows services with minimal effort. This blog post introduces how this process is done.

By 
Gunnar Peipman user avatar
Gunnar Peipman
·
Jun. 22, 18 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
45.2K Views

Join the DZone community and get the full member experience.

Join For Free

asp.net core 2.1 introduces a new application host for windows services. we can now run asp.net core applications as windows services with minimal effort. this blog post introduces how it is done and how to build and run windows services on asp.net core without any need for dirty hacks.

creating a default web application

we start with new default asp.net core 2.1 web application.

 i didn't configure https as this is a sample application and it does nothing important.

by default, the  program    class looks like this.

public class program
{
    public static void main(string[] args)
    {
        createwebhostbuilder(args).build().run();
    }

    public static iwebhostbuilder createwebhostbuilder(string[] args) =>
        webhost.createdefaultbuilder(args)
            .usestartup<startup>();
}

now we have working default application and it's time to focus on the windows service.

running an asp.net core application as a windows service

running the application as a windows service takes some effort before we can open the browser and see it running under the service. first, we have to specify a runtime for our application, as asp.net core also supports operating systems and architectures where windows services don't run. for this, we have to modify the project file.

<project sdk="microsoft.net.sdk.web">

  <propertygroup>
    <targetframework>netcoreapp2.1</targetframework>
    <runtimeidentifier>win7-x64</runtimeidentifier>
  </propertygroup>

  <itemgroup>
    <packagereference include="microsoft.aspnetcore.app" />
  </itemgroup>

</project>

next, add a reference to the nuget package  microsoft.aspnetcore.hosting.windowsservices  . this package has everything needed to run an asp.net core application as a windows service.

 nb!  for me, the newest version 2.1.1 of microsoft.aspnetcore.hosting.windowsservices conflicted with asp.net core 2.1.0 and i went with version 2.1.0 instead.

we also have to modify the  main()    method of the  program    class. in its simplest form, the  main()    method looks like this.

public static void main(string[] args)
{
    var pathtoexe = process.getcurrentprocess().mainmodule.filename;
    var pathtocontentroot = path.getdirectoryname(pathtoexe);

    var host = webhost.createdefaultbuilder(args)
        .usecontentroot(pathtocontentroot)
        .usestartup<startup>()
        .build();

    host.runasservice();
}

all we have to do now is to publish our application, register it as a windows service, and start the service.

running the application as a service or on a console

those who have built windows services before, know very well that the debugging of services can be a pain in one specific anatomical area as after building the service one has to deploy new version of it, attach a debugger, etc. there is simple way around - we make our windows service run also as a console application that is easy to run on debugger from visual studio.

we can apply the same trick also with asp.net core application that is running as windows service.

public static void main(string[] args)
{
    var isservice = !(debugger.isattached || args.contains("--console"));
    var pathtocontentroot = directory.getcurrentdirectory();
    var webhostargs = args.where(arg => arg != "--console").toarray();

    if (isservice)
    {
        var pathtoexe = process.getcurrentprocess().mainmodule.filename;
        pathtocontentroot = path.getdirectoryname(pathtoexe);
    }

    var host = webhost.createdefaultbuilder(webhostargs)
        .usecontentroot(pathtocontentroot)
        .usestartup<startup>()
        .build();

    if (isservice)
    {
        host.runasservice();
    }
    else
    {
        host.run();
    }
}

the code shown may seem a little tricky. here are my explanations:

  • to run the application on the console from visual studio we control if the debugger is attached. if we want to run the application as a console application outside of visual studio we can use the  -console    argument.
  • when the application runs as a web application under the web server, we must use the current directory as the content root. but when the application runs as a service, we need an executable path as the content root.
  • we remove the  -console    argument, as asp.net core expects all arguments to be name-value pairs.

now try to run the application from visual studio. it starts as a usual web application.

making the application run as a windows service

to make the application run as windows service we need some additional steps.

  1. publish the application to some folder.
  2. open the command line in administrative permissions.
  3. register the application as a windows service using t command (space after "binpath=" is mandatory)  sc create aspnetwindowsservice binpath= "path to my application exe"   
  4.   start service:  sc start aspnetwindowsservice  .
  5. when the service starts, open the browser and navigate to  http://localhost:5000  to see the web application running.

before releasing a new version of the service, the currently running instance must be stopped. for this, we can use the command  sc stop aspnetwindowsservice  . to remove the service, run the following command:  sc delete aspnetwindowsservice  .

wrapping up

with the new microsoft.aspnetcore.hosting.windowsservices nuget package, it is easy to run asp.net core applications as windows services. we had to modify project file a little bit and make the application's  main()    method in order to understand if an application runs as a service or a console application. using this trick we are able to build a web application on visual studio and run it as a typical web application. our burden to get a web application running as windows service was minimal.

application ASP.NET Core Web Service ASP.NET

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Deploy an ASP.NET Core Application in the IBM Cloud Code Engine
  • Alexa Skill With .NET Core
  • GDPR Compliance With .NET: Securing Data the Right Way

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!