作为Windows服务部署时,不会读取asp.net Core 2 Web API appsetting.json值

Mit*_*tch 1 c# configuration asp.net-core asp.net-core-webapi asp.net-core-mvc-2.0

我正在运行asp.net core 2 Web API作为Windows服务。通过IIS调试时,我可以读取配置值,没有问题。

但是,一旦将其作为服务运行,我将无法获得任何价值。

appsettings.json

{
  "Database": {
    "DatabaseName": "testdb",
    "DatabaseServer": "localhost",
    "DatabaseUserName": "admin",
    "DatabasePassword": "admin"
  }
}

 public string GetConnectionString()
    {
        var databaseName = Configuration["Database:DatabaseName"];
        var databaseServer = Configuration["Database:DatabaseServer"];
        var username = Configuration["Database:DatabaseUserName"];
        var password = Configuration["Database:DatabasePassword"];


        return $"Data Source={databaseServer};Initial Catalog={databaseName};Persist Security Info=True;User ID={username};Password={password};MultipleActiveResultSets=True";
    }
Run Code Online (Sandbox Code Playgroud)

不知道为什么发布应用程序后为什么我无法读取这些值。在发布的appsettings.json文件中,值在那里。

这是我的startup.cs。我的印象是,我不必在新的asp.net核心2中引用appSettings.json文件。感谢您的帮助。

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        AutoMapper.Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<InventoryTransaction, Models.InventoryTransactionModel>();
            cfg.CreateMap<ReasonCode, Models.ReasonCodeModel>();
            cfg.CreateMap<InventoryTransaction, Models.InventoryTransactionForCreationModel>();
            cfg.CreateMap<InventoryTransactionForCreationModel, InventoryTransaction>();
        });
        services.AddScoped<IInventoryTransactionRepository, InventoryTransactionRepository>();
        services.AddSingleton<IConfiguration>(Configuration);
        services.AddDbContext<VPSInventoryContext>(options => options.UseSqlServer(GetConnectionString()));

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();
        loggerFactory.AddNLog();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();

    }

    public string GetConnectionString()
    {
        var databaseName = Configuration["Database:DatabaseName"];
        var databaseServer = Configuration["Database:DatabaseServer"];
        var username = Configuration["Database:DatabaseUserName"];
        var password = Configuration["Database:DatabasePassword"];


        return $"Data Source={databaseServer};Initial Catalog={databaseName};Persist Security Info=True;User ID={username};Password={password};MultipleActiveResultSets=True";
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我作为Windows服务运行的Program.cs。

public class Program
{
    public static void Main(string[] args)
    {
        if (Debugger.IsAttached || args.Contains("--debug"))
        {
            BuildWebHost(args).Run();
        }
        else
        {
            BuildWebHost(args).RunAsService();
        }
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}
Run Code Online (Sandbox Code Playgroud)

Cod*_*ler 6

当您将应用程序作为服务启动时,工作目录将设置为系统目录,例如C:\Windows\System32\。配置文件在同一目录中查找。只要在那里不存在,您就会加载空配置。

要修复此问题,只需将工作目录设置为您的应用程序所在的目录:

public static void Main(string[] args)
{
    if (Debugger.IsAttached || args.Contains("--debug"))
    {
        BuildWebHost(args).Run();
    }
    else
    {
        var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
        Directory.SetCurrentDirectory(path);
        BuildWebHost(args).RunAsService();
    }
}
Run Code Online (Sandbox Code Playgroud)