MVC 3 getting values from AppSettings in web.config

前端 未结 2 1612
梦谈多话
梦谈多话 2021-02-11 16:08

In normal ASP.NET Web forms sites I would use web.configs \"appsettings\" to add application setting data to a site. However, I am not able to retrieve setting values this way w

相关标签:
2条回答
  • 2021-02-11 16:24

    Are you ever calling set? I'm guessing it never gets called, so the private variable never gets the value from the config.

    Try it this way (just retrieve the value in the get, no set needed):

    public string ClientSecret
    {    
      get { return System.Configuration.ConfigurationManager.AppSettings["ClientSecret"]; }    
    }
    
    0 讨论(0)
  • 2021-02-11 16:31

    Usually I'm using AppSettings static class to access those parameters. Something like this:

    public static class AppSettings 
    {
    
        public static string ClientSecret
        {
            get
            {
                return Setting<string>("ClientSecret");
            }
        }
    
        private static T Setting<T>(string name)
        {
            string value = ConfigurationManager.AppSettings[name];
    
            if (value == null)
            {
                throw new Exception(String.Format("Could not find setting '{0}',", name));
            }
    
            return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
        }
    }
    
    0 讨论(0)
提交回复
热议问题