15

Should be simple, but whatever I try returns null:

const string key = "system.web";

var sectionTry1 = WebConfigurationManager.GetSection(key);

var sectionTry2 = ConfigurationManager.GetSection(key);

I'm sure I have done this before.

I am using MVC if this makes a difference.

Paul Hiles
  • 9,558
  • 7
  • 51
  • 76

3 Answers3

29

Was being an idiot - system.web is not a config section but a config group. If I change the key to an actual section, then both methods work fine. Here's the one using ConfigurationManager:

const string outputCacheSettingsKey = "system.web/caching/outputCacheSettings";           

var outputCacheSettingsSection = ConfigurationManager.GetSection(outputCacheSettingsKey) as OutputCacheSettingsSection;
Paul Hiles
  • 9,558
  • 7
  • 51
  • 76
7

I think accessing system.web is slightly different to accessing appSettings.

Try this:

string configPath = "/MyAppRoot";

Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);

IdentitySection section = (IdentitySection)config.GetSection("system.web/identity");

You need to cast the relevant section of system.web you're trying to access to a particular type.

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
RPM1984
  • 72,246
  • 58
  • 225
  • 350
6

This worked for me:

public Int32 GetmaxRequestLength()
{
    // Set the maximum file size for uploads in bytes.
    var section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
    // return length converted to kbytes or return default value as specified
    return (Int32) Math.Round((decimal)(section != null ? (double)section.MaxRequestLength * 1024 / 1000 : 5.120), 2);
}
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
Raine
  • 61
  • 1
  • 1
  • `ConfigurationManager.GetSection` reads ***machine.config*** or ***web.config*** ? Only I want read ***web.config*** – Kiquenet Oct 18 '17 at 13:05