【问题标题】:How to access the username and password from appsettings file to program.cs in c# [duplicate]如何在c#中从appsettings文件访问用户名和密码到program.cs [重复]
【发布时间】:2021-08-01 08:36:35
【问题描述】:

我正在实现一个控制台应用程序来构建应用程序池状态。我参考了check the status of IIS Application Pool 从数据库中获取用户名和密码,我想从 appsettings.json 中获取它们。

我遇到的问题是值(用户名 jandi)没有传递给 program.cs,它传递了一个空值。

我已经包含了我的代码。

program.cs

using Serilog;
using System;
using System.Configuration;
using System.DirectoryServices;
using System.Timers;

namespace processstatus
{
    class Program
    {
       

        static void Main(string[] args)
        {
            const double interval60Minutes = 5 * 5 * 1000; // milliseconds to one hour
            Timer checkForTime = new Timer(interval60Minutes);
            checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
            checkForTime.Enabled = true;
            Console.WriteLine("Waiting..");
            Console.ReadLine();
        }

        public static void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
        {
            GetApplicationPoolNames();
        }

        public static string GetApplicationPoolNames()
        {
            string UName = ConfigurationManager.AppSettings["User"];
            string Pwd = ConfigurationManager.AppSettings["Pass"];
            string ServerName = ConfigurationManager.AppSettings["Server"];
            DirectoryEntries appPools = null;
            try
            {
                appPools = new DirectoryEntry("IIS://" + ServerName + "/W3SVC/AppPools", UName, Pwd).Children;
            }
            catch (Exception ex)
            {
                Log.Error("serviceLogic -> InsertStatus() -> IIS Pool App Region -> DirectoryEntries -> Error: ", ex.Message.ToString());
            }

            Log.Information("IIS App Pool Section Started for " + System.Environment.MachineName.ToString());

            try
            {
                foreach (DirectoryEntry appPool in appPools)
                {
                    Log.Information("App Pool : " + appPool.Name.ToString());
                    int intStatus = 0;
                    string status = "";
                    try
                    {
                        if (appPool.Name.ToString().ToLower().Trim() == ConfigurationManager.AppSettings["Server"].ToString().ToLower().Trim())
                        {
                            Log.Information("Process Started for App Pool : " + appPool.Name.ToString());

                            intStatus = (int)appPool.InvokeGet("AppPoolState");
                            switch (intStatus)
                            {
                                case 2:
                                    status = "Running";
                                    break;
                                case 4:
                                    status = "Stopped";
                                    break;
                                default:
                                    status = "Unknown";
                                    break;
                            }

                            //Store status info to db or file Logic goes here..

                            //Start App pool, If any application pool status is not Running.
                            if (status != "Running")
                                appPool.Invoke("Start", null);

                            Log.Information("Process Completed for App Pool : " + appPool.Name.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("serviceLogic -> InsertStatus() -> IIS Pool App Region -> Error: ", ex.Message);

                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("serviceLogic -> InsertStatus() -> IIS Pool App Region -> DirectoryEntries -> Error: ", ex.Message);
            }
            return "Message";
        }
    }
}

Appsettings.json 文件

   {
  "AppSettings": {
    "User": "jandi",
    "Pass": "jandi123",
    "Server": "abc"
  }
}

有人可以告诉我上面代码中的错误吗?

【问题讨论】:

  • 这是 .NET Framework、.NET Core 还是 .NET 5?另外,ConfigurationManager 用于 .NET Framework 的 app.config 文件,而不是用于 .NET Core 的 appsettings.json 文件
  • @Progman我已经推荐过了。所以为了做到这一点,是否必须使用mvc架构?有没有办法在不使用mvc的情况下完成要求?
  • 你不需要使用 ASP.NET Core。你可以只安装 Microsoft.Extensions.Configuration 包(nuget.org/packages?q=microsoft.extensions.configuration),我认为 Json 应该足够了
  • ConfigurationManager 读取 app.config 文件而不是 appsettings.json。您需要使用 appSettings 部分添加适当的 app.config,然后您的代码应该可以工作(前提是它可以正确编译)
  • @Steve 非常感谢您指出我的错误。它成功了!!!

标签: c# appsettings


【解决方案1】:

对于 .NET Core 控制台应用程序,您可以使用 Microsoft.Extensions.Configuration 来读取 appsettings.json 文件,正如 cmets 中已经指出的那样。我已经使用了几次,它似乎工作得很好。然后你可以在你的 Program 类中使用这样的东西:

private static IConfiguration _configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", true, true)
    .Build();

然后您可以通过 _configuration 变量读取 appsettings 变量。

【讨论】:

    猜你喜欢
    • 2018-02-19
    • 2018-01-10
    • 2018-07-18
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多