在通过Windows服务托管应用程序时,我无法加载正确的appsettings。<>。json文件。
下面是用于托管Windows服务的设置。
https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-2.2
public class Program
{
#region ServiceOrConsole
public static void Main(string[] args)
{
var isService = !(Debugger.IsAttached || args.Contains("--console"));
var builder = CreateWebHostBuilder(args.Where(arg => arg != "--console").ToArray());
if (isService)
{
var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);
//use a path to the app's published location instead of Directory.GetCurrentDirectory().
builder.UseContentRoot(pathToContentRoot);
}
var host = builder.Build();
if (isService)
{
host.RunAsCustomService();
}
else
{
host.Run();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var cfg = Startup.GetConfiguration();
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://localhost:1234");
}
#endregion
}
下面的Get方法应根据环境显示正确的Test值。
问题是它总是从appsettings.json
文件中读取。
[Route("api/[controller]")]
[ApiController]
public class CfgController : ControllerBase
{
private IConfiguration _configuration;
public CfgController (IConfiguration configuration)
{
_configuration = configuration;
}
[HttpGet]
public IActionResult Get()
{
var test =_configuration.GetValue<string>("Test");
return Ok($"{test}");
}
}
appsettings.json
{
"Test": "default"
}
appsettings.Development.json
{
"Test": "default dev"
}
下面是我尝试的尝试,无济于事
1将args传递给Windows服务
sc start "My service" --environment "Development"
2在下面设置Windows环境,然后启动服务
set ASPNETCORE_ENVIRONMENT=Development
sc start "My service"
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-2.2 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/index?view=aspnetcore-2.2#json-configuration-provider https://andrewlock.net/how-to-set-the-hosting-environment-in-asp-net-core/
答案 0 :(得分:0)
一个老问题,但是我今天遇到了同样的问题,很难找到有用的答案。无论如何,即使appsettings.json
设置为appsettings.Development.json
,我的Windows服务似乎总是从ASPNETCORE_ENVIRONMENT
而不是Development
读取。
我的研究表明,首先,我对Windows服务一无所知。第二,Windows服务的默认设置是在SYSTEM
用户下运行(请选中任务管理器->详细信息-> [您的服务])。这个answer很有帮助:
以SYSTEM(LocalSystem,NT_AUTHORITY \ SYSTEM)运行的程序将具有一个环境,该环境是根据在HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Control \ Session Manager \ Environment和HKEY_USERS.DEFAULT \ Environment中指定的变量构建的。确保要“查看”的变量在这些位置之一中定义,并且可以访问。
一个简单的解决方案是使用注册表管理器或命令提示符将ASPNETCORE_ENVIRONMENT
设置为全局环境变量:
setx /M ASPNETCORE_ENVIRONMENT Development
我认为也可以以特定用户身份运行该服务。