Search code examples
asp.net-web-apiweb-confignancy

Reading appsettings in Nancy


I have a web api in Nancy 1.4.3. I have defined some settings in web.config under applicationSettings section. I was wondering how can I read these settings in a Nancy module (or Bootstrapper)? Because the conventional ways of reading these settings as in MVC/WebAPI are not available in Nancy. Please consider that I am using Nancy 1.4.3 not Nancy 2x and .net 4.6.1 not .net core.

For simplicity, I am writing how the applicationSettings section looks like in web.config:

<applicationSettings>
    <Applicaton1.Properties.Settings>
       <setting name="DefaultUserID" serializeAs="String">
         <value>BatchReader</value>
       </setting>
      <setting name="DefaultPaymentFrequencyCode" serializeAs="String">
        <value>0</value>
      </setting>
     <setting name="DefaultPaymentTypeCode" serializeAs="String">
        <value>1</value>
     </setting>
</Application1.Properties.Settings>


Solution

  • You should be able to read it exactly the same as any asp.net app. Make sure you add reference to:

    System.Configuration
    

    In Web.config add your key:

    <appSettings>
    <add key="key" value="hello key" />
    </appSettings>
    

    Include System.Configuration in your Bootstrapper:

    namespace Test
    {
        using System.Configuration;
        using Nancy;
        using Nancy.Authentication.Forms;
        using Nancy.Bootstrapper;
        using Nancy.TinyIoc;
    
    
        public class Bootstrapper : DefaultNancyBootstrapper
        {
            protected override void ApplicationStartup (TinyIoCContainer container,
                                                       IPipelines pipelines)
            {
                base.ApplicationStartup (container, pipelines);
                StaticConfiguration.DisableErrorTraces = false;
                StaticConfiguration.EnableRequestTracing = true;
            }
    
            protected override void ConfigureApplicationContainer (TinyIoCContainer
                                                                  container)
            {
                base.ConfigureApplicationContainer (container);
    
                var key = ConfigurationManager
                                           .AppSettings.Get ("key")
    
            }
    
    
            protected override void ConfigureRequestContainer (TinyIoCContainer container,
                                                              NancyContext context)
            {
                base.ConfigureRequestContainer (container, context);
    
            }
    
            protected override void RequestStartup (TinyIoCContainer container,
                                                   IPipelines pipelines,
                                                   NancyContext context)
            {
                base.RequestStartup (container, pipelines, context);
            }
        }
    }
    

    Thats it! :)