ईवेंट्स
Power BI DataViz World Championship
14 फ़र॰, 4 pm - 31 मार्च, 4 pm
प्रवेश करने के 4 अवसरों के साथ, आप एक सम्मेलन पैकेज जीत सकते हैं और लास वेगास में लाइव ग्रैंड फिनाले में जगह बना सकते हैं
अधिक जानेंयह ब्राउज़र अब समर्थित नहीं है.
नवीनतम सुविधाओं, सुरक्षा अपडेट और तकनीकी सहायता का लाभ लेने के लिए Microsoft Edge में अपग्रेड करें.
नोट
This isn't the latest version of this article. For the current release, see the .NET 9 version of this article.
चेतावनी
This version of ASP.NET Core is no longer supported. For more information, see the .NET and .NET Core Support Policy. For the current release, see the .NET 9 version of this article.
महत्वपूर्ण
This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
For the current release, see the .NET 9 version of this article.
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.
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:
Update Program.cs to call AddWindowsService. When the app is running as a Windows Service, AddWindowsService
:
WindowsServiceLifetime
.CreateDefaultBuilder
to build the host.Logging:EventLog:LogLevel:Default
key in appsettings.json
/appsettings.{Environment}.json
or other configuration provider.Consider the following ServiceA
class:
namespace SampleApp.Services;
public class ServiceA : BackgroundService
{
public ServiceA(ILoggerFactory loggerFactory)
{
Logger = loggerFactory.CreateLogger<ServiceA>();
}
public ILogger Logger { get; }
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Logger.LogInformation("ServiceA is starting.");
stoppingToken.Register(() => Logger.LogInformation("ServiceA is stopping."));
while (!stoppingToken.IsCancellationRequested)
{
Logger.LogInformation("ServiceA is doing background work.");
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
Logger.LogInformation("ServiceA has stopped.");
}
}
The following Program.cs
calls AddHostedService
to register ServiceA
:
using SampleApp.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddWindowsService();
builder.Services.AddHostedService<ServiceA>();
var app = builder.Build();
app.MapRazorPages();
app.Run();
The following sample apps accompany this topic:
For MVC guidance, see the articles under Overview of ASP.NET Core MVC and Migrate from ASP.NET Core 2.2 to 3.0.
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:
<Project Sdk="Microsoft.NET.Sdk.Web">
If the service only executes background tasks (for example, hosted services), specify the Worker SDK in the project file:
<Project Sdk="Microsoft.NET.Sdk.Worker">
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 <IsTransformWebConfigDisabled>
property set to true
.
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
</PropertyGroup>
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 <PropertyGroup>
that contains the target framework:
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
To publish for multiple RIDs:
For more information, see .NET Core RID Catalog.
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:
New-LocalUser -Name {SERVICE NAME}
On Windows OS earlier than the Windows 10 October 2018 Update (version 1809/build 10.0.17763):
powershell -Command "New-LocalUser -Name {SERVICE NAME}"
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.
For more information, see Microsoft.PowerShell.LocalAccounts and Service User Accounts.
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.
To establish Log on as a service rights for a service user account:
{DOMAIN OR COMPUTER NAME\USER}
) in the object name field and select OK to add the user to the policy.Use PowerShell commands to register a service. From an administrative PowerShell 6 command shell, execute the following commands:
$acl = Get-Acl "{EXE PATH}"
$aclRuleArgs = "{DOMAIN OR COMPUTER NAME\USER}", "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "{EXE PATH}"
New-Service -Name {SERVICE NAME} -BinaryPathName "{EXE FILE PATH} --contentRoot {EXE FOLDER PATH}" -Credential "{DOMAIN OR COMPUTER NAME\USER}" -Description "{DESCRIPTION}" -DisplayName "{DISPLAY NAME}" -StartupType Automatic
{EXE PATH}
: Path of the app's executable on the host (for example, d:\myservice
). Don't include the app's executable file name in the path. A trailing slash isn't required.{DOMAIN OR COMPUTER NAME\USER}
: Service user account (for example, Contoso\ServiceUser
).{SERVICE NAME}
: Service name (for example, MyService
).{EXE FILE PATH}
: The app's full executable path (for example, d:\myservice\myservice.exe
). Include the executable's file name with extension.{EXE FOLDER PATH}
: The app's full executable folder path (for example d:\myservice
).{DESCRIPTION}
: Service description (for example, My sample service
).{DISPLAY NAME}
: Service display name (for example, My Service
).Start a service with the following PowerShell 6 command:
Start-Service -Name {SERVICE NAME}
The command takes a few seconds to start the service.
To check the status of a service, use the following PowerShell 6 command:
Get-Service -Name {SERVICE NAME}
The status is reported as one of the following values:
Starting
Running
Stopping
Stopped
Stop a service with the following PowerShell 6 command:
Stop-Service -Name {SERVICE NAME}
After a short delay to stop a service, remove a service with the following PowerShell 6 command:
Remove-Service -Name {SERVICE NAME}
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.
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.
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 IHostEnvironment.ContentRootPath or ContentRootFileProvider to locate an app's resources.
When the app runs as a service, UseWindowsService sets the ContentRootPath to AppContext.BaseDirectory.
The app's default settings files, appsettings.json
and appsettings.{Environment}.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:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("custom_settings.json");
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
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.
Specify an absolute path with SetBasePath when using an IConfigurationBuilder to the folder containing the files.
To troubleshoot a Windows Service app, see Troubleshoot and debug ASP.NET Core projects.
New-Service
PowerShell command.Access the System and Application Event Logs:
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.
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.
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.
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:
.\EnableDumps {APPLICATION EXE} c:\dumps
Run the app under the conditions that cause the crash to occur.
After the crash has occurred, run the DisableDumps PowerShell script:
.\DisableDumps {APPLICATION EXE}
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).
When an app 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.
A dump can be analyzed using several approaches. For more information, see Analyzing a User-Mode Dump File.
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.
View or download sample code (how to download)
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:
The app requires a package reference for Microsoft.Extensions.Hosting.WindowsServices.
IHostBuilder.UseWindowsService
is called when building the host. If the app is running as a Windows Service, the method:
WindowsServiceLifetime
.CreateDefaultBuilder
to build the host.Logging:EventLog:LogLevel:Default
key in appsettings.json
/appsettings.{Environment}.json
or other configuration provider.In Program.cs
:
ContentRootPath
UseWindowsService
using Microsoft.Extensions.Hosting.WindowsServices;
using SampleApp.Services;
var options = new WebApplicationOptions
{
Args = args,
ContentRootPath = WindowsServiceHelpers.IsWindowsService()
? AppContext.BaseDirectory : default
};
var builder = WebApplication.CreateBuilder(options);
builder.Services.AddRazorPages();
builder.Services.AddHostedService<ServiceA>();
builder.Services.AddHostedService<ServiceB>();
builder.Host.UseWindowsService();
var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
await app.RunAsync();
The following sample apps accompany this topic:
For MVC guidance, see the articles under Overview of ASP.NET Core MVC and Migrate from ASP.NET Core 2.2 to 3.0.
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:
<Project Sdk="Microsoft.NET.Sdk.Web">
If the service only executes background tasks (for example, hosted services), specify the Worker SDK in the project file:
<Project Sdk="Microsoft.NET.Sdk.Worker">
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 <IsTransformWebConfigDisabled>
property set to true
.
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
</PropertyGroup>
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 <PropertyGroup>
that contains the target framework:
<RuntimeIdentifier>win7-x64</RuntimeIdentifier>
To publish for multiple RIDs:
For more information, see .NET Core RID Catalog.
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:
New-LocalUser -Name {SERVICE NAME}
On Windows OS earlier than the Windows 10 October 2018 Update (version 1809/build 10.0.17763):
powershell -Command "New-LocalUser -Name {SERVICE NAME}"
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.
For more information, see Microsoft.PowerShell.LocalAccounts and Service User Accounts.
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.
To establish Log on as a service rights for a service user account:
{DOMAIN OR COMPUTER NAME\USER}
) in the object name field and select OK to add the user to the policy.Use PowerShell commands to register a service. From an administrative PowerShell 6 command shell, execute the following commands:
$acl = Get-Acl "{EXE PATH}"
$aclRuleArgs = "{DOMAIN OR COMPUTER NAME\USER}", "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "{EXE PATH}"
New-Service -Name {SERVICE NAME} -BinaryPathName "{EXE FILE PATH} --contentRoot {EXE FOLDER PATH}" -Credential "{DOMAIN OR COMPUTER NAME\USER}" -Description "{DESCRIPTION}" -DisplayName "{DISPLAY NAME}" -StartupType Automatic
{EXE PATH}
: Path of the app's executable on the host (for example, d:\myservice
). Don't include the app's executable file name in the path. A trailing slash isn't required.{DOMAIN OR COMPUTER NAME\USER}
: Service user account (for example, Contoso\ServiceUser
).{SERVICE NAME}
: Service name (for example, MyService
).{EXE FILE PATH}
: The app's full executable path (for example, d:\myservice\myservice.exe
). Include the executable's file name with extension.{EXE FOLDER PATH}
: The app's full executable folder path (for example d:\myservice
).{DESCRIPTION}
: Service description (for example, My sample service
).{DISPLAY NAME}
: Service display name (for example, My Service
).Start a service with the following PowerShell 6 command:
Start-Service -Name {SERVICE NAME}
The command takes a few seconds to start the service.
To check the status of a service, use the following PowerShell 6 command:
Get-Service -Name {SERVICE NAME}
The status is reported as one of the following values:
Starting
Running
Stopping
Stopped
Stop a service with the following PowerShell 6 command:
Stop-Service -Name {SERVICE NAME}
After a short delay to stop a service, remove a service with the following PowerShell 6 command:
Remove-Service -Name {SERVICE NAME}
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.
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.
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 IHostEnvironment.ContentRootPath or ContentRootFileProvider to locate an app's resources.
When the app runs as a service, UseWindowsService sets the ContentRootPath to AppContext.BaseDirectory.
The app's default settings files, appsettings.json
and appsettings.{Environment}.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:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("custom_settings.json");
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
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.
Specify an absolute path with SetBasePath when using an IConfigurationBuilder to the folder containing the files.
To troubleshoot a Windows Service app, see Troubleshoot and debug ASP.NET Core projects.
New-Service
PowerShell command.Access the System and Application Event Logs:
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.
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.
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.
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:
.\EnableDumps {APPLICATION EXE} c:\dumps
Run the app under the conditions that cause the crash to occur.
After the crash has occurred, run the DisableDumps PowerShell script:
.\DisableDumps {APPLICATION EXE}
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).
When an app 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.
A dump can be analyzed using several approaches. For more information, see Analyzing a User-Mode Dump File.
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.
View or download sample code (how to download)
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:
The app requires a package reference for Microsoft.Extensions.Hosting.WindowsServices.
IHostBuilder.UseWindowsService
is called when building the host. If the app is running as a Windows Service, the method:
WindowsServiceLifetime
.CreateDefaultBuilder
to build the host.Logging:EventLog:LogLevel:Default
key in appsettings.json
/appsettings.{Environment}.json
or other configuration provider.In CreateHostBuilder
of Program.cs
:
Host.CreateDefaultBuilder(args)
.UseWindowsService()
...
The following sample apps accompany this topic:
For MVC guidance, see the articles under Overview of ASP.NET Core MVC and Migrate from ASP.NET Core 2.2 to 3.0.
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:
<Project Sdk="Microsoft.NET.Sdk.Web">
If the service only executes background tasks (for example, hosted services), specify the Worker SDK in the project file:
<Project Sdk="Microsoft.NET.Sdk.Worker">
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 <IsTransformWebConfigDisabled>
property set to true
.
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
</PropertyGroup>
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 <PropertyGroup>
that contains the target framework:
<RuntimeIdentifier>win7-x64</RuntimeIdentifier>
To publish for multiple RIDs:
For more information, see .NET Core RID Catalog.
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:
New-LocalUser -Name {SERVICE NAME}
On Windows OS earlier than the Windows 10 October 2018 Update (version 1809/build 10.0.17763):
powershell -Command "New-LocalUser -Name {SERVICE NAME}"
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.
For more information, see Microsoft.PowerShell.LocalAccounts and Service User Accounts.
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.
To establish Log on as a service rights for a service user account:
{DOMAIN OR COMPUTER NAME\USER}
) in the object name field and select OK to add the user to the policy.Use PowerShell commands to register a service. From an administrative PowerShell 6 command shell, execute the following commands:
$acl = Get-Acl "{EXE PATH}"
$aclRuleArgs = "{DOMAIN OR COMPUTER NAME\USER}", "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "{EXE PATH}"
New-Service -Name {SERVICE NAME} -BinaryPathName "{EXE FILE PATH}" -Credential "{DOMAIN OR COMPUTER NAME\USER}" -Description "{DESCRIPTION}" -DisplayName "{DISPLAY NAME}" -StartupType Automatic
{EXE PATH}
: Path of the app's executable on the host (for example, d:\myservice
). Don't include the app's executable file name in the path. A trailing slash isn't required.{DOMAIN OR COMPUTER NAME\USER}
: Service user account (for example, Contoso\ServiceUser
).{SERVICE NAME}
: Service name (for example, MyService
).{EXE FILE PATH}
: The app's full executable path (for example, d:\myservice\myservice.exe
). Include the executable's file name with extension.{DESCRIPTION}
: Service description (for example, My sample service
).{DISPLAY NAME}
: Service display name (for example, My Service
).Start a service with the following PowerShell 6 command:
Start-Service -Name {SERVICE NAME}
The command takes a few seconds to start the service.
To check the status of a service, use the following PowerShell 6 command:
Get-Service -Name {SERVICE NAME}
The status is reported as one of the following values:
Starting
Running
Stopping
Stopped
Stop a service with the following PowerShell 6 command:
Stop-Service -Name {SERVICE NAME}
After a short delay to stop a service, remove a service with the following PowerShell 6 command:
Remove-Service -Name {SERVICE NAME}
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.
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.
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 IHostEnvironment.ContentRootPath or ContentRootFileProvider to locate an app's resources.
When the app runs as a service, UseWindowsService sets the ContentRootPath to AppContext.BaseDirectory.
The app's default settings files, appsettings.json
and appsettings.{Environment}.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:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("custom_settings.json");
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
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.
Specify an absolute path with SetBasePath when using an IConfigurationBuilder to the folder containing the files.
To troubleshoot a Windows Service app, see Troubleshoot and debug ASP.NET Core projects.
New-Service
PowerShell command.Access the System and Application Event Logs:
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.
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.
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.
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:
.\EnableDumps {APPLICATION EXE} c:\dumps
Run the app under the conditions that cause the crash to occur.
After the crash has occurred, run the DisableDumps PowerShell script:
.\DisableDumps {APPLICATION EXE}
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).
When an app 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.
A dump can be analyzed using several approaches. For more information, see Analyzing a User-Mode Dump File.
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.
View or download sample code (how to download)
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:
The app requires a package reference for Microsoft.Extensions.Hosting.WindowsServices.
IHostBuilder.UseWindowsService
is called when building the host. If the app is running as a Windows Service, the method:
WindowsServiceLifetime
.CreateDefaultBuilder
to build the host.Logging:EventLog:LogLevel:Default
key in appsettings.json
/appsettings.{Environment}.json
or other configuration provider.In CreateHostBuilder
of Program.cs
:
Host.CreateDefaultBuilder(args)
.UseWindowsService()
...
The following sample apps accompany this topic:
For MVC guidance, see the articles under Overview of ASP.NET Core MVC and Migrate from ASP.NET Core 2.2 to 3.0.
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:
<Project Sdk="Microsoft.NET.Sdk.Web">
If the service only executes background tasks (for example, hosted services), specify the Worker SDK in the project file:
<Project Sdk="Microsoft.NET.Sdk.Worker">
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 <IsTransformWebConfigDisabled>
property set to true
.
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
</PropertyGroup>
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 <PropertyGroup>
that contains the target framework:
<RuntimeIdentifier>win7-x64</RuntimeIdentifier>
To publish for multiple RIDs:
For more information, see .NET Core RID Catalog.
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:
New-LocalUser -Name {SERVICE NAME}
On Windows OS earlier than the Windows 10 October 2018 Update (version 1809/build 10.0.17763):
powershell -Command "New-LocalUser -Name {SERVICE NAME}"
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.
For more information, see Microsoft.PowerShell.LocalAccounts and Service User Accounts.
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.
To establish Log on as a service rights for a service user account:
{DOMAIN OR COMPUTER NAME\USER}
) in the object name field and select OK to add the user to the policy.Use PowerShell commands to register a service. From an administrative PowerShell 6 command shell, execute the following commands:
$acl = Get-Acl "{EXE PATH}"
$aclRuleArgs = "{DOMAIN OR COMPUTER NAME\USER}", "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
$acl | Set-Acl "{EXE PATH}"
New-Service -Name {SERVICE NAME} -BinaryPathName "{EXE FILE PATH}" -Credential "{DOMAIN OR COMPUTER NAME\USER}" -Description "{DESCRIPTION}" -DisplayName "{DISPLAY NAME}" -StartupType Automatic
{EXE PATH}
: Path of the app's executable on the host (for example, d:\myservice
). Don't include the app's executable file name in the path. A trailing slash isn't required.{DOMAIN OR COMPUTER NAME\USER}
: Service user account (for example, Contoso\ServiceUser
).{SERVICE NAME}
: Service name (for example, MyService
).{EXE FILE PATH}
: The app's full executable path (for example, d:\myservice\myservice.exe
). Include the executable's file name with extension.{DESCRIPTION}
: Service description (for example, My sample service
).{DISPLAY NAME}
: Service display name (for example, My Service
).Start a service with the following PowerShell 6 command:
Start-Service -Name {SERVICE NAME}
The command takes a few seconds to start the service.
To check the status of a service, use the following PowerShell 6 command:
Get-Service -Name {SERVICE NAME}
The status is reported as one of the following values:
Starting
Running
Stopping
Stopped
Stop a service with the following PowerShell 6 command:
Stop-Service -Name {SERVICE NAME}
After a short delay to stop a service, remove a service with the following PowerShell 6 command:
Remove-Service -Name {SERVICE NAME}
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.
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.
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 IHostEnvironment.ContentRootPath or ContentRootFileProvider to locate an app's resources.
When the app runs as a service, UseWindowsService sets the ContentRootPath to AppContext.BaseDirectory.
The app's default settings files, appsettings.json
and appsettings.{Environment}.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:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("custom_settings.json");
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
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.
Specify an absolute path with SetBasePath when using an IConfigurationBuilder to the folder containing the files.
To troubleshoot a Windows Service app, see Troubleshoot and debug ASP.NET Core projects.
New-Service
PowerShell command.Access the System and Application Event Logs:
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.
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.
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.
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:
.\EnableDumps {APPLICATION EXE} c:\dumps
Run the app under the conditions that cause the crash to occur.
After the crash has occurred, run the DisableDumps PowerShell script:
.\DisableDumps {APPLICATION EXE}
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).
When an app 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.
A dump can be analyzed using several approaches. For more information, see Analyzing a User-Mode Dump File.
ASP.NET Core प्रतिक्रिया
ASP.NET Core एक ओपन सोर्स प्रोजेक्ट है. प्रतिक्रिया प्रदान करने के लिए लिंक का चयन करें:
ईवेंट्स
Power BI DataViz World Championship
14 फ़र॰, 4 pm - 31 मार्च, 4 pm
प्रवेश करने के 4 अवसरों के साथ, आप एक सम्मेलन पैकेज जीत सकते हैं और लास वेगास में लाइव ग्रैंड फिनाले में जगह बना सकते हैं
अधिक जानेंप्रशिक्षण
मॉड्यूल
App Service Diagnostics के साथ वेब अनुप्रयोग डाउन परिदृश्यों का समस्या निवारण करें - Training
वेब ऐप डाउन, क्रैश मॉनिटरिंग का उपयोग करें और जिन्न से समस्या निवारण के लिए पूछें। अनुप्रयोग और प्लेटफ़ॉर्म उपलब्धता की निगरानी करने, हैंडल न किए गए अपवादों की पहचान करने, मेमोरी डंप और कॉलस्टैक कैप्चर करने और जाँच और निदान के क्षेत्रों को ढूँढने के लिए इन उपकरणों का उपयोग करें.