How do I access Configuration in any class in ASP.NET Core?

前端 未结 11 1706
梦如初夏
梦如初夏 2020-11-29 01:09

I have gone through configuration documentation on ASP.NET core. Documentation says you can access configuration from anywhere in the application.

Below is Startup.c

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 01:22

    I have to read own parameters by startup.
    That has to be there before the WebHost is started (as I need the “to listen” url/IP and port from the parameter file and apply it to the WebHost). Further, I need the settings public in the whole application.

    After searching for a while (no complete example found, only snippets) and after various try-and-error's, I have decided to do it the “old way" with an own .ini file.
    So.. if you want to use your own .ini file and/or set the "to listen url/IP" your own and/or need the settings public, this is for you...

    Complete example, valid for core 2.1 (mvc):

    Create an .ini-file - example:

    [Startup]
    URL=http://172.16.1.201:22222
    [Parameter]
    *Dummy1=gew7623
    Dummy1=true
    Dummy2=1

    whereby the Dummyx are only included as example for other date types than string (and also to test the case “wrong param” (see code below).

    Added a code file in the root of the project, to store the global variables:

    namespace MatrixGuide
    {
        public static class GV
        {
            // In this class all gobals are defined
    
            static string _cURL;
            public static string cURL // URL (IP + Port) on that the application has to listen
            {
                get { return _cURL; }
                set { _cURL = value; }
            }
    
            static bool _bdummy1;
            public static bool bdummy1 // 
            {
                get { return _bdummy1; }
                set { _bdummy1 = value; }
            }
    
            static int _idummy1;
            public static int idummy1 // 
            {
                get { return _idummy1; }
                set { _idummy1 = value; }
            }
    
            static bool _bFehler_Ini;
            public static bool bFehler_Ini // 
            {
                get { return _bFehler_Ini; }
                set { _bFehler_Ini = value; }
            }
    
            // add further  GV variables here..
        }
        // Add further classes here... 
    }
    

    Changed the code in program.cs (before CreateWebHostBuilder()):

    namespace MatrixGuide
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                // Read .ini file and overtake the contend in globale
                // Do it in an try-catch to be able to react to errors
                GV.bFehler_Ini = false;
                try
                {
                    var iniconfig = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddIniFile("matrixGuide.ini", optional: false, reloadOnChange: true)
                    .Build();
                    string cURL = iniconfig.GetValue("Startup:URL");
                    bool bdummy1 = iniconfig.GetValue("Parameter:Dummy1");
                    int idummy2 = iniconfig.GetValue("Parameter:Dummy2");
                    //
                    GV.cURL = cURL;
                    GV.bdummy1 = bdummy1;
                    GV.idummy1 = idummy2;
                }
                catch (Exception e)
                {
                    GV.bFehler_Ini = true;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("!! Fehler beim Lesen von MatrixGuide.ini !!");
                    Console.WriteLine("Message:" + e.Message);
                    if (!(e.InnerException != null))
                    {
                        Console.WriteLine("InnerException: " + e.InnerException.ToString());
                    }
    
                    Console.ForegroundColor = ConsoleColor.White;
                }
                // End .ini file processing
                //
                CreateWebHostBuilder(args).Build().Run();
            }
    
            public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                .UseStartup() //;
                .UseUrls(GV.cURL, "http://localhost:5000"); // set the to use URL from .ini -> no impact to IISExpress
    
        }
    }
    

    This way:

    • My Application config is separated from the appsettings.json and I have no sideeffects to fear, if MS does changes in future versions ;-)
    • I have my settings in global variables
    • I am able to set the "to listen url" for each device, the applicaton run's on (my dev machine, the intranet server and the internet server)
    • I'm able to deactivate settings, the old way (just set a * before)
    • I'm able to react, if something is wrong in the .ini file (e.g. type mismatch)
      If - e.g. - a wrong type is set (e.g. the *Dummy1=gew7623 is activated instead of the Dummy1=true) the host shows red information's on the console (including the exception) and I' able to react also in the application (GV.bFehler_Ini ist set to true, if there are errors with the .ini)

提交回复
热议问题