How to read system.web section from web.config

眉间皱痕 提交于 2019-12-09 08:23:33

问题


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.


回答1:


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;



回答2:


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.




回答3:


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);
}


来源:https://stackoverflow.com/questions/3021877/how-to-read-system-web-section-from-web-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!