App path windows service

Содержание
  1. Modifying the “Path to executable” of a windows service
  2. 8 Answers 8
  3. How to find windows service exe path
  4. 10 Answers 10
  5. Host ASP.NET Core in a Windows Service
  6. Prerequisites
  7. Worker Service template
  8. App configuration
  9. Deployment type
  10. Framework-dependent deployment (FDD)
  11. Self-contained deployment (SCD)
  12. Service user account
  13. Log on as a service rights
  14. Create and manage the Windows Service
  15. Create a service
  16. Start a service
  17. Determine a service’s status
  18. Stop a service
  19. Remove a service
  20. Proxy server and load balancer scenarios
  21. Configure endpoints
  22. Current directory and content root
  23. Use ContentRootPath or ContentRootFileProvider
  24. Store a service’s files in a suitable location on disk
  25. Troubleshoot
  26. Common errors
  27. System and Application Event Logs
  28. Run the app at a command prompt
  29. Clear package caches
  30. Slow or hanging app
  31. App crashes or encounters an exception
  32. App hangs, fails during startup, or runs normally
  33. Analyze the dump
  34. Additional resources
  35. Prerequisites
  36. App configuration
  37. Deployment type
  38. Framework-dependent deployment (FDD)
  39. Self-contained deployment (SCD)
  40. Service user account
  41. Log on as a service rights
  42. Create and manage the Windows Service
  43. Create a service
  44. Start a service
  45. Determine a service’s status
  46. Stop a service
  47. Remove a service
  48. Handle starting and stopping events
  49. Proxy server and load balancer scenarios
  50. Configure endpoints
  51. Current directory and content root
  52. Set the content root path to the app’s folder
  53. Store a service’s files in a suitable location on disk
  54. Troubleshoot
  55. Common errors
  56. System and Application Event Logs
  57. Run the app at a command prompt
  58. Clear package caches
  59. Slow or hanging app
  60. App crashes or encounters an exception
  61. App hangs, fails during startup, or runs normally
  62. Analyze the dump
  63. Additional resources
  64. Prerequisites
  65. App configuration
  66. Deployment type
  67. Framework-dependent deployment (FDD)
  68. Self-contained deployment (SCD)
  69. Service user account
  70. Log on as a service rights
  71. Create and manage the Windows Service
  72. Create a service
  73. Start a service
  74. Determine a service’s status
  75. Stop a service
  76. Remove a service
  77. Handle starting and stopping events
  78. Proxy server and load balancer scenarios
  79. Configure endpoints
  80. Current directory and content root
  81. Set the content root path to the app’s folder
  82. Store a service’s files in a suitable location on disk
  83. Troubleshoot
  84. Common errors
  85. System and Application Event Logs
  86. Run the app at a command prompt
  87. Clear package caches
  88. Slow or hanging app
  89. App crashes or encounters an exception
  90. App hangs, fails during startup, or runs normally
  91. Analyze the dump

Modifying the “Path to executable” of a windows service

I’d like to modify the path to my application, but doing so breaks it because the service still points to the old location.

By going to Administrative Tools > Services you can open a properties dialog and view the Path to executable , but there is no way to change it.

Is there any way a user can modify the service path without having to reinstall the application ?

8 Answers 8

There is also this approach seen on SuperUser which uses the sc command line instead of modifying the registry:

Note: the space after binPath= is important. You can also query the current configuration using:

This displays output similar to:

It involves editing the registry, but service information can be found in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services . Find the service you want to redirect, locate the ImagePath subkey and change that value.

You could also do it with PowerShell:

Open Run(win+R) , type «Regedit.exe» , to open «Registry Editor», go to

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services

find «Apache2.4» open the folder find the «ImagePath» in the right side, open «ImagePath» under «value Data» put the following path:

«C:\xampp\apache\bin\httpd.exe» -k runservice foe XAMPP for others point to the location where Apache is installed and inside locate the bin folder «C:(Apache installed location)\bin\httpd.exe» -k runservice

Slight modification to this @CodeMaker ‘s answer, for anyone like me who is trying to modify a MongoDB service to use authentication.

When I looked at the «Path to executable» in «Services» the executed line already contained speech marks. So I had to make minor modification to his example.

  1. Type Services in Windows
  2. Find MongoDB (or the service you want to change) and open the service, making sure to stop it.
  3. Make a note of the Service Name (not the display name)
  4. Look up and copy the «Path to executable» and copy it.

For me the path was (note the speech marks)

How to find windows service exe path

I have a windows service and I need to create directory to store some info. The directory path must be relative to the windows service exe file. How can get this exe file path ?

10 Answers 10

Tip: If you want to find startup path of installed windows service, look here from registry .

There are keys about windows service

Instead of using a directory relative to the executable, and therefore needing admin privileges, why not use the common application data directory, which is accessible through

This way your app doesn’t need write access to its own install directory, which makes you more secure.

svchost.exe is the executable which runs your service which is in system32. Hence we need to get to the module which is being run by the process.

The default directory for a windows service is the System32 folder. In your service, though, you can change the current directory to the directory that you specified in the service installation by doing the following in your OnStart:

Edit: an even simpler method (but I haven’t tested yet):

This did the trick for me

This will return you the correct path even if running under LocalSystem account which defaults to system32:

If you want to get access of Program Files folder or any other using programming you should use the below code which is provide rights to specific folder.

Host ASP.NET Core in a Windows Service

An ASP.NET Core app can be hosted on Windows as a Windows Service without using IIS. When hosted as a Windows Service, the app automatically starts after server reboots.

Prerequisites

Worker Service template

The ASP.NET Core Worker Service template provides a starting point for writing long running service apps. To use the template as a basis for a Windows Service app:

  1. Create a Worker Service app from the .NET Core template.
  2. Follow the guidance in the App configuration section to update the Worker Service app so that it can run as a Windows Service.
  • Visual Studio
  • Visual Studio for Mac
  • .NET Core CLI
  1. Create a new project.
  2. Select Worker Service. Select Next.
  3. Provide a project name in the Project name field or accept the default project name. Select Create.
  4. In the Create a new Worker service dialog, select Create.
  1. Create a new project.
  2. Select App under .NET Core in the sidebar.
  3. Select Worker under ASP.NET Core. Select Next.
  4. Select .NET Core 3.0 or later for the Target Framework. Select Next.
  5. Provide a name in the Project Name field. Select Create.

Use the Worker Service ( worker ) template with the dotnet new command from a command shell. In the following example, a Worker Service app is created named ContosoWorker . A folder for the ContosoWorker app is created automatically when the command is executed.

App configuration

IHostBuilder.UseWindowsService is called when building the host. If the app is running as a Windows Service, the method:

  • Sets the host lifetime to WindowsServiceLifetime .
  • Sets the content root to AppContext.BaseDirectory. For more information, see the Current directory and content root section.
  • Enables logging to the event log:
    • The application name is used as the default source name.
    • The default log level is Warning or higher for an app based on an ASP.NET Core template that calls CreateDefaultBuilder to build the host.
    • Override the default log level with the Logging:EventLog:LogLevel:Default key in appsettings.json/appsettings..json or other configuration provider.
    • Only administrators can create new event sources. When an event source can’t be created using the application name, a warning is logged to the Application source and event logs are disabled.

In CreateHostBuilder of Program.cs:

The following sample apps accompany this topic:

  • Background Worker Service Sample: A non-web app sample based on the Worker Service template that uses hosted services for background tasks.
  • Web App Service Sample: A Razor Pages web app sample that runs as a Windows Service with hosted services for background tasks.

Deployment type

For information and advice on deployment scenarios, see .NET Core application deployment.

For a web app-based service that uses the Razor Pages or MVC frameworks, specify the Web SDK in the project file:

If the service only executes background tasks (for example, hosted services), specify the Worker SDK in the project file:

Framework-dependent deployment (FDD)

Framework-dependent deployment (FDD) relies on the presence of a shared system-wide version of .NET Core on the target system. When the FDD scenario is adopted following the guidance in this article, the SDK produces an executable (.exe), called a framework-dependent executable.

If using the Web SDK, a web.config file, which is normally produced when publishing an ASP.NET Core app, is unnecessary for a Windows Services app. To disable the creation of the web.config file, add the property set to true .

Self-contained deployment (SCD)

Self-contained deployment (SCD) doesn’t rely on the presence of a shared framework on the host system. The runtime and the app’s dependencies are deployed with the app.

A Windows Runtime Identifier (RID) is included in the

that contains the target framework:

To publish for multiple RIDs:

  • Provide the RIDs in a semicolon-delimited list.
  • Use the property name (plural).

For more information, see .NET Core RID Catalog.

Service user account

To create a user account for a service, use the New-LocalUser cmdlet from an administrative PowerShell 6 command shell.

On Windows 10 October 2018 Update (version 1809/build 10.0.17763) or later:

On Windows OS earlier than the Windows 10 October 2018 Update (version 1809/build 10.0.17763):

Provide a strong password when prompted.

Unless the -AccountExpires parameter is supplied to the New-LocalUser cmdlet with an expiration DateTime, the account doesn’t expire.

An alternative approach to managing users when using Active Directory is to use Managed Service Accounts. For more information, see Group Managed Service Accounts Overview.

Log on as a service rights

To establish Log on as a service rights for a service user account:

  1. Open the Local Security Policy editor by running secpol.msc.
  2. Expand the Local Policies node and select User Rights Assignment.
  3. Open the Log on as a service policy.
  4. Select Add User or Group.
  5. Provide the object name (user account) using either of the following approaches:
    1. Type the user account ( ) in the object name field and select OK to add the user to the policy.
    2. Select Advanced. Select Find Now. Select the user account from the list. Select OK. Select OK again to add the user to the policy.
  6. Select OK or Apply to accept the changes.

Create and manage the Windows Service

Create a service

Use PowerShell commands to register a service. From an administrative PowerShell 6 command shell, execute the following commands:

  • : Path to the app’s folder on the host (for example, d:\myservice ). Don’t include the app’s executable in the path. A trailing slash isn’t required.
  • : Service user account (for example, Contoso\ServiceUser ).
  • : Service name (for example, MyService ).
  • : The app’s executable path (for example, d:\myservice\myservice.exe ). Include the executable’s file name with extension.
  • : Service description (for example, My sample service ).
  • : Service display name (for example, My Service ).

Start a service

Start a service with the following PowerShell 6 command:

The command takes a few seconds to start the service.

Determine a service’s status

To check the status of a service, use the following PowerShell 6 command:

The status is reported as one of the following values:

Stop a service

Stop a service with the following Powershell 6 command:

Remove a service

After a short delay to stop a service, remove a service with the following Powershell 6 command:

Proxy server and load balancer scenarios

Services that interact with requests from the Internet or a corporate network and are behind a proxy or load balancer might require additional configuration. For more information, see Configure ASP.NET Core to work with proxy servers and load balancers.

Configure endpoints

By default, ASP.NET Core binds to http://localhost:5000 . Configure the URL and port by setting the ASPNETCORE_URLS environment variable.

For additional URL and port configuration approaches, see the relevant server article:

The preceding guidance covers support for HTTPS endpoints. For example, configure the app for HTTPS when authentication is used with a Windows Service.

Use of the ASP.NET Core HTTPS development certificate to secure a service endpoint isn’t supported.

Current directory and content root

The current working directory returned by calling GetCurrentDirectory for a Windows Service is the C:\WINDOWS\system32 folder. The system32 folder isn’t a suitable location to store a service’s files (for example, settings files). Use one of the following approaches to maintain and access a service’s assets and settings files.

Use ContentRootPath or ContentRootFileProvider

The app’s default settings files, appsettings.json and appsettings..json, are loaded from the app’s content root by calling CreateDefaultBuilder during host construction.

For other settings files loaded by developer code in ConfigureAppConfiguration, there’s no need to call SetBasePath. In the following example, the custom_settings.json file exists in the app’s content root and is loaded without explicitly setting a base path:

Don’t attempt to use GetCurrentDirectory to obtain a resource path because a Windows Service app returns the C:\WINDOWS\system32 folder as its current directory.

Store a service’s files in a suitable location on disk

Specify an absolute path with SetBasePath when using an IConfigurationBuilder to the folder containing the files.

Troubleshoot

Common errors

  • An old or pre-release version of PowerShell is in use.
  • The registered service doesn’t use the app’s published output from the dotnet publish command. Output of the dotnet build command isn’t supported for app deployment. Published assets are found in either of the following folders depending on the deployment type:
    • bin/Release//publish (FDD)
    • bin/Release///publish (SCD)
  • The service isn’t in the RUNNING state.
  • The paths to resources that the app uses (for example, certificates) are incorrect. The base path of a Windows Service is c:\Windows\System32.
  • The user doesn’t have Log on as a service rights.
  • The user’s password is expired or incorrectly passed when executing the New-Service PowerShell command.
  • The app requires ASP.NET Core authentication but isn’t configured for secure connections (HTTPS).
  • The request URL port is incorrect or not configured correctly in the app.

System and Application Event Logs

Access the System and Application Event Logs:

  1. Open the Start menu, search for Event Viewer, and select the Event Viewer app.
  2. In Event Viewer, open the Windows Logs node.
  3. Select System to open the System Event Log. Select Application to open the Application Event Log.
  4. Search for errors associated with the failing app.

Run the app at a command prompt

Many startup errors don’t produce useful information in the event logs. You can find the cause of some errors by running the app at a command prompt on the hosting system. To log additional detail from the app, lower the log level or run the app in the Development environment.

Clear package caches

A functioning app may fail immediately after upgrading either the .NET Core SDK on the development machine or changing package versions within the app. In some cases, incoherent packages may break an app when performing major upgrades. Most of these issues can be fixed by following these instructions:

Delete the bin and obj folders.

Clear the package caches by executing dotnet nuget locals all —clear from a command shell.

Clearing package caches can also be accomplished with the nuget.exe tool and executing the command nuget locals all -clear . nuget.exe isn’t a bundled install with the Windows desktop operating system and must be obtained separately from the NuGet website.

Restore and rebuild the project.

Delete all of the files in the deployment folder on the server prior to redeploying the app.

Slow or hanging app

A crash dump is a snapshot of the system’s memory and can help determine the cause of an app crash, startup failure, or slow app.

App crashes or encounters an exception

Obtain and analyze a dump from Windows Error Reporting (WER):

Create a folder to hold crash dump files at c:\dumps .

Run the EnableDumps PowerShell script with the application executable name:

Run the app under the conditions that cause the crash to occur.

After the crash has occurred, run the DisableDumps PowerShell script:

After an app crashes and dump collection is complete, the app is allowed to terminate normally. The PowerShell script configures WER to collect up to five dumps per app.

Crash dumps might take up a large amount of disk space (up to several gigabytes each).

App hangs, fails during startup, or runs normally

When an app hangs (stops responding but doesn’t crash), fails during startup, or runs normally, see User-Mode Dump Files: Choosing the Best Tool to select an appropriate tool to produce the dump.

Analyze the dump

A dump can be analyzed using several approaches. For more information, see Analyzing a User-Mode Dump File.

Additional resources

  • Kestrel endpoint configuration (includes HTTPS configuration and SNI support)
  • Kestrel endpoint configuration (includes HTTPS configuration and SNI support)

An ASP.NET Core app can be hosted on Windows as a Windows Service without using IIS. When hosted as a Windows Service, the app automatically starts after server reboots.

Prerequisites

App configuration

To test and debug when running outside of a service, add code to determine if the app is running as a service or a console app. Inspect if the debugger is attached or a —console switch is present. If either condition is true (the app isn’t run as a service), call Run. If the conditions are false (the app is run as a service):

  • Call SetCurrentDirectory and use a path to the app’s published location. Don’t call GetCurrentDirectory to obtain the path because a Windows Service app returns the C:\WINDOWS\system32 folder when GetCurrentDirectory is called. For more information, see the Current directory and content root section. This step is performed before the app is configured in CreateWebHostBuilder .
  • Call RunAsService to run the app as a service.

Because the Command-line Configuration Provider requires name-value pairs for command-line arguments, the —console switch is removed from the arguments before CreateDefaultBuilder receives the arguments.

To write to the Windows Event Log, add the EventLog provider to ConfigureLogging. Set the logging level with the Logging:LogLevel:Default key in the appsettings.Production.json file.

In the following example from the sample app, RunAsCustomService is called instead of RunAsService in order to handle lifetime events within the app. For more information, see the Handle starting and stopping events section.

Deployment type

For information and advice on deployment scenarios, see .NET Core application deployment.

For a web app-based service that uses the Razor Pages or MVC frameworks, specify the Web SDK in the project file:

If the service only executes background tasks (for example, hosted services), specify the Worker SDK in the project file:

Framework-dependent deployment (FDD)

Framework-dependent deployment (FDD) relies on the presence of a shared system-wide version of .NET Core on the target system. When the FDD scenario is adopted following the guidance in this article, the SDK produces an executable (.exe), called a framework-dependent executable.

The Windows Runtime Identifier (RID) ( ) contains the target framework. In the following example, the RID is set to win7-x64 . The property is set to false . These properties instruct the SDK to generate an executable (.exe) file for Windows and an app that depends on the shared .NET Core framework.

A web.config file, which is normally produced when publishing an ASP.NET Core app, is unnecessary for a Windows Services app. To disable the creation of the web.config file, add the property set to true .

Self-contained deployment (SCD)

Self-contained deployment (SCD) doesn’t rely on the presence of a shared framework on the host system. The runtime and the app’s dependencies are deployed with the app.

A Windows Runtime Identifier (RID) is included in the

that contains the target framework:

To publish for multiple RIDs:

  • Provide the RIDs in a semicolon-delimited list.
  • Use the property name (plural).

For more information, see .NET Core RID Catalog.

A property is set to true :

Service user account

To create a user account for a service, use the New-LocalUser cmdlet from an administrative PowerShell 6 command shell.

On Windows 10 October 2018 Update (version 1809/build 10.0.17763) or later:

On Windows OS earlier than the Windows 10 October 2018 Update (version 1809/build 10.0.17763):

Provide a strong password when prompted.

Unless the -AccountExpires parameter is supplied to the New-LocalUser cmdlet with an expiration DateTime, the account doesn’t expire.

An alternative approach to managing users when using Active Directory is to use Managed Service Accounts. For more information, see Group Managed Service Accounts Overview.

Log on as a service rights

To establish Log on as a service rights for a service user account:

  1. Open the Local Security Policy editor by running secpol.msc.
  2. Expand the Local Policies node and select User Rights Assignment.
  3. Open the Log on as a service policy.
  4. Select Add User or Group.
  5. Provide the object name (user account) using either of the following approaches:
    1. Type the user account ( ) in the object name field and select OK to add the user to the policy.
    2. Select Advanced. Select Find Now. Select the user account from the list. Select OK. Select OK again to add the user to the policy.
  6. Select OK or Apply to accept the changes.

Create and manage the Windows Service

Create a service

Use PowerShell commands to register a service. From an administrative PowerShell 6 command shell, execute the following commands:

  • : Path to the app’s folder on the host (for example, d:\myservice ). Don’t include the app’s executable in the path. A trailing slash isn’t required.
  • : Service user account (for example, Contoso\ServiceUser ).
  • : Service name (for example, MyService ).
  • : The app’s executable path (for example, d:\myservice\myservice.exe ). Include the executable’s file name with extension.
  • : Service description (for example, My sample service ).
  • : Service display name (for example, My Service ).

Start a service

Start a service with the following PowerShell 6 command:

The command takes a few seconds to start the service.

Determine a service’s status

To check the status of a service, use the following PowerShell 6 command:

The status is reported as one of the following values:

Stop a service

Stop a service with the following Powershell 6 command:

Remove a service

After a short delay to stop a service, remove a service with the following Powershell 6 command:

Handle starting and stopping events

Create a class that derives from WebHostService with the OnStarting , OnStarted , and OnStopping methods:

Create an extension method for IWebHost that passes the CustomWebHostService to Run:

In Program.Main , call the RunAsCustomService extension method instead of RunAsService:

To see the location of RunAsService in Program.Main , refer to the code sample shown in the Deployment type section.

Proxy server and load balancer scenarios

Services that interact with requests from the Internet or a corporate network and are behind a proxy or load balancer might require additional configuration. For more information, see Configure ASP.NET Core to work with proxy servers and load balancers.

Configure endpoints

By default, ASP.NET Core binds to http://localhost:5000 . Configure the URL and port by setting the ASPNETCORE_URLS environment variable.

For additional URL and port configuration approaches, see the relevant server article:

The preceding guidance covers support for HTTPS endpoints. For example, configure the app for HTTPS when authentication is used with a Windows Service.

Use of the ASP.NET Core HTTPS development certificate to secure a service endpoint isn’t supported.

Current directory and content root

The current working directory returned by calling GetCurrentDirectory for a Windows Service is the C:\WINDOWS\system32 folder. The system32 folder isn’t a suitable location to store a service’s files (for example, settings files). Use one of the following approaches to maintain and access a service’s assets and settings files.

Set the content root path to the app’s folder

The ContentRootPath is the same path provided to the binPath argument when a service is created. Instead of calling GetCurrentDirectory to create paths to settings files, call SetCurrentDirectory with the path to the app’s content root.

In Program.Main , determine the path to the folder of the service’s executable and use the path to establish the app’s content root:

Store a service’s files in a suitable location on disk

Specify an absolute path with SetBasePath when using an IConfigurationBuilder to the folder containing the files.

Troubleshoot

Common errors

  • An old or pre-release version of PowerShell is in use.
  • The registered service doesn’t use the app’s published output from the dotnet publish command. Output of the dotnet build command isn’t supported for app deployment. Published assets are found in either of the following folders depending on the deployment type:
    • bin/Release//publish (FDD)
    • bin/Release///publish (SCD)
  • The service isn’t in the RUNNING state.
  • The paths to resources that the app uses (for example, certificates) are incorrect. The base path of a Windows Service is c:\Windows\System32.
  • The user doesn’t have Log on as a service rights.
  • The user’s password is expired or incorrectly passed when executing the New-Service PowerShell command.
  • The app requires ASP.NET Core authentication but isn’t configured for secure connections (HTTPS).
  • The request URL port is incorrect or not configured correctly in the app.

System and Application Event Logs

Access the System and Application Event Logs:

  1. Open the Start menu, search for Event Viewer, and select the Event Viewer app.
  2. In Event Viewer, open the Windows Logs node.
  3. Select System to open the System Event Log. Select Application to open the Application Event Log.
  4. Search for errors associated with the failing app.

Run the app at a command prompt

Many startup errors don’t produce useful information in the event logs. You can find the cause of some errors by running the app at a command prompt on the hosting system. To log additional detail from the app, lower the log level or run the app in the Development environment.

Clear package caches

A functioning app may fail immediately after upgrading either the .NET Core SDK on the development machine or changing package versions within the app. In some cases, incoherent packages may break an app when performing major upgrades. Most of these issues can be fixed by following these instructions:

Delete the bin and obj folders.

Clear the package caches by executing dotnet nuget locals all —clear from a command shell.

Clearing package caches can also be accomplished with the nuget.exe tool and executing the command nuget locals all -clear . nuget.exe isn’t a bundled install with the Windows desktop operating system and must be obtained separately from the NuGet website.

Restore and rebuild the project.

Delete all of the files in the deployment folder on the server prior to redeploying the app.

Slow or hanging app

A crash dump is a snapshot of the system’s memory and can help determine the cause of an app crash, startup failure, or slow app.

App crashes or encounters an exception

Obtain and analyze a dump from Windows Error Reporting (WER):

Create a folder to hold crash dump files at c:\dumps .

Run the EnableDumps PowerShell script with the application executable name:

Run the app under the conditions that cause the crash to occur.

After the crash has occurred, run the DisableDumps PowerShell script:

After an app crashes and dump collection is complete, the app is allowed to terminate normally. The PowerShell script configures WER to collect up to five dumps per app.

Crash dumps might take up a large amount of disk space (up to several gigabytes each).

App hangs, fails during startup, or runs normally

When an app hangs (stops responding but doesn’t crash), fails during startup, or runs normally, see User-Mode Dump Files: Choosing the Best Tool to select an appropriate tool to produce the dump.

Analyze the dump

A dump can be analyzed using several approaches. For more information, see Analyzing a User-Mode Dump File.

Additional resources

  • Kestrel endpoint configuration (includes HTTPS configuration and SNI support)
  • ASP.NET Core Web Host
  • Troubleshoot and debug ASP.NET Core projects

An ASP.NET Core app can be hosted on Windows as a Windows Service without using IIS. When hosted as a Windows Service, the app automatically starts after server reboots.

Prerequisites

App configuration

To test and debug when running outside of a service, add code to determine if the app is running as a service or a console app. Inspect if the debugger is attached or a —console switch is present. If either condition is true (the app isn’t run as a service), call Run. If the conditions are false (the app is run as a service):

  • Call SetCurrentDirectory and use a path to the app’s published location. Don’t call GetCurrentDirectory to obtain the path because a Windows Service app returns the C:\WINDOWS\system32 folder when GetCurrentDirectory is called. For more information, see the Current directory and content root section. This step is performed before the app is configured in CreateWebHostBuilder .
  • Call RunAsService to run the app as a service.

Because the Command-line Configuration Provider requires name-value pairs for command-line arguments, the —console switch is removed from the arguments before CreateDefaultBuilder receives the arguments.

To write to the Windows Event Log, add the EventLog provider to ConfigureLogging. Set the logging level with the Logging:LogLevel:Default key in the appsettings.Production.json file.

In the following example from the sample app, RunAsCustomService is called instead of RunAsService in order to handle lifetime events within the app. For more information, see the Handle starting and stopping events section.

Deployment type

For information and advice on deployment scenarios, see .NET Core application deployment.

For a web app-based service that uses the Razor Pages or MVC frameworks, specify the Web SDK in the project file:

If the service only executes background tasks (for example, hosted services), specify the Worker SDK in the project file:

Framework-dependent deployment (FDD)

Framework-dependent deployment (FDD) relies on the presence of a shared system-wide version of .NET Core on the target system. When the FDD scenario is adopted following the guidance in this article, the SDK produces an executable (.exe), called a framework-dependent executable.

The Windows Runtime Identifier (RID) ( ) contains the target framework. In the following example, the RID is set to win7-x64 . The property is set to false . These properties instruct the SDK to generate an executable (.exe) file for Windows and an app that depends on the shared .NET Core framework.

The property is set to true . This property provides the service with an activation path (an executable, .exe) for an FDD.

A web.config file, which is normally produced when publishing an ASP.NET Core app, is unnecessary for a Windows Services app. To disable the creation of the web.config file, add the property set to true .

Self-contained deployment (SCD)

Self-contained deployment (SCD) doesn’t rely on the presence of a shared framework on the host system. The runtime and the app’s dependencies are deployed with the app.

A Windows Runtime Identifier (RID) is included in the

that contains the target framework:

To publish for multiple RIDs:

  • Provide the RIDs in a semicolon-delimited list.
  • Use the property name (plural).

For more information, see .NET Core RID Catalog.

A property is set to true :

Service user account

To create a user account for a service, use the New-LocalUser cmdlet from an administrative PowerShell 6 command shell.

On Windows 10 October 2018 Update (version 1809/build 10.0.17763) or later:

On Windows OS earlier than the Windows 10 October 2018 Update (version 1809/build 10.0.17763):

Provide a strong password when prompted.

Unless the -AccountExpires parameter is supplied to the New-LocalUser cmdlet with an expiration DateTime, the account doesn’t expire.

An alternative approach to managing users when using Active Directory is to use Managed Service Accounts. For more information, see Group Managed Service Accounts Overview.

Log on as a service rights

To establish Log on as a service rights for a service user account:

  1. Open the Local Security Policy editor by running secpol.msc.
  2. Expand the Local Policies node and select User Rights Assignment.
  3. Open the Log on as a service policy.
  4. Select Add User or Group.
  5. Provide the object name (user account) using either of the following approaches:
    1. Type the user account ( ) in the object name field and select OK to add the user to the policy.
    2. Select Advanced. Select Find Now. Select the user account from the list. Select OK. Select OK again to add the user to the policy.
  6. Select OK or Apply to accept the changes.

Create and manage the Windows Service

Create a service

Use PowerShell commands to register a service. From an administrative PowerShell 6 command shell, execute the following commands:

  • : Path to the app’s folder on the host (for example, d:\myservice ). Don’t include the app’s executable in the path. A trailing slash isn’t required.
  • : Service user account (for example, Contoso\ServiceUser ).
  • : Service name (for example, MyService ).
  • : The app’s executable path (for example, d:\myservice\myservice.exe ). Include the executable’s file name with extension.
  • : Service description (for example, My sample service ).
  • : Service display name (for example, My Service ).

Start a service

Start a service with the following PowerShell 6 command:

The command takes a few seconds to start the service.

Determine a service’s status

To check the status of a service, use the following PowerShell 6 command:

The status is reported as one of the following values:

Stop a service

Stop a service with the following Powershell 6 command:

Remove a service

After a short delay to stop a service, remove a service with the following Powershell 6 command:

Handle starting and stopping events

Create a class that derives from WebHostService with the OnStarting , OnStarted , and OnStopping methods:

Create an extension method for IWebHost that passes the CustomWebHostService to Run:

In Program.Main , call the RunAsCustomService extension method instead of RunAsService:

To see the location of RunAsService in Program.Main , refer to the code sample shown in the Deployment type section.

Proxy server and load balancer scenarios

Services that interact with requests from the Internet or a corporate network and are behind a proxy or load balancer might require additional configuration. For more information, see Configure ASP.NET Core to work with proxy servers and load balancers.

Configure endpoints

By default, ASP.NET Core binds to http://localhost:5000 . Configure the URL and port by setting the ASPNETCORE_URLS environment variable.

For additional URL and port configuration approaches, see the relevant server article:

The preceding guidance covers support for HTTPS endpoints. For example, configure the app for HTTPS when authentication is used with a Windows Service.

Use of the ASP.NET Core HTTPS development certificate to secure a service endpoint isn’t supported.

Current directory and content root

The current working directory returned by calling GetCurrentDirectory for a Windows Service is the C:\WINDOWS\system32 folder. The system32 folder isn’t a suitable location to store a service’s files (for example, settings files). Use one of the following approaches to maintain and access a service’s assets and settings files.

Set the content root path to the app’s folder

The ContentRootPath is the same path provided to the binPath argument when a service is created. Instead of calling GetCurrentDirectory to create paths to settings files, call SetCurrentDirectory with the path to the app’s content root.

In Program.Main , determine the path to the folder of the service’s executable and use the path to establish the app’s content root:

Store a service’s files in a suitable location on disk

Specify an absolute path with SetBasePath when using an IConfigurationBuilder to the folder containing the files.

Troubleshoot

Common errors

  • An old or pre-release version of PowerShell is in use.
  • The registered service doesn’t use the app’s published output from the dotnet publish command. Output of the dotnet build command isn’t supported for app deployment. Published assets are found in either of the following folders depending on the deployment type:
    • bin/Release//publish (FDD)
    • bin/Release///publish (SCD)
  • The service isn’t in the RUNNING state.
  • The paths to resources that the app uses (for example, certificates) are incorrect. The base path of a Windows Service is c:\Windows\System32.
  • The user doesn’t have Log on as a service rights.
  • The user’s password is expired or incorrectly passed when executing the New-Service PowerShell command.
  • The app requires ASP.NET Core authentication but isn’t configured for secure connections (HTTPS).
  • The request URL port is incorrect or not configured correctly in the app.

System and Application Event Logs

Access the System and Application Event Logs:

  1. Open the Start menu, search for Event Viewer, and select the Event Viewer app.
  2. In Event Viewer, open the Windows Logs node.
  3. Select System to open the System Event Log. Select Application to open the Application Event Log.
  4. Search for errors associated with the failing app.

Run the app at a command prompt

Many startup errors don’t produce useful information in the event logs. You can find the cause of some errors by running the app at a command prompt on the hosting system. To log additional detail from the app, lower the log level or run the app in the Development environment.

Clear package caches

A functioning app may fail immediately after upgrading either the .NET Core SDK on the development machine or changing package versions within the app. In some cases, incoherent packages may break an app when performing major upgrades. Most of these issues can be fixed by following these instructions:

Delete the bin and obj folders.

Clear the package caches by executing dotnet nuget locals all —clear from a command shell.

Clearing package caches can also be accomplished with the nuget.exe tool and executing the command nuget locals all -clear . nuget.exe isn’t a bundled install with the Windows desktop operating system and must be obtained separately from the NuGet website.

Restore and rebuild the project.

Delete all of the files in the deployment folder on the server prior to redeploying the app.

Slow or hanging app

A crash dump is a snapshot of the system’s memory and can help determine the cause of an app crash, startup failure, or slow app.

App crashes or encounters an exception

Obtain and analyze a dump from Windows Error Reporting (WER):

Create a folder to hold crash dump files at c:\dumps .

Run the EnableDumps PowerShell script with the application executable name:

Run the app under the conditions that cause the crash to occur.

After the crash has occurred, run the DisableDumps PowerShell script:

After an app crashes and dump collection is complete, the app is allowed to terminate normally. The PowerShell script configures WER to collect up to five dumps per app.

Crash dumps might take up a large amount of disk space (up to several gigabytes each).

App hangs, fails during startup, or runs normally

When an app hangs (stops responding but doesn’t crash), fails during startup, or runs normally, see User-Mode Dump Files: Choosing the Best Tool to select an appropriate tool to produce the dump.

Analyze the dump

A dump can be analyzed using several approaches. For more information, see Analyzing a User-Mode Dump File.

Читайте также:  Как сделать красивую панель управления windows 10
Оцените статью