【发布时间】:2018-08-08 19:20:34
【问题描述】:
我的网站上有几个地方有帮助文本告诉用户允许的最大文件上传大小是多少。我希望能够让它成为动态的,这样如果我更改 web.config 文件中的请求限制,我就不必去在一堆地方更改表单说明。这可以使用 ConfigurationManager 或其他东西吗?
【问题讨论】:
标签: asp.net configurationmanager
我的网站上有几个地方有帮助文本告诉用户允许的最大文件上传大小是多少。我希望能够让它成为动态的,这样如果我更改 web.config 文件中的请求限制,我就不必去在一堆地方更改表单说明。这可以使用 ConfigurationManager 或其他东西吗?
【问题讨论】:
标签: asp.net configurationmanager
由于您没有提供任何进一步的详细信息:正如 here 指出的那样,您有 2 个选项可以为整个应用程序设置大小限制。
根据您需要采取不同的方法:
如果您使用<httpRuntime maxRequestLength="" />,您可以通过WebConfigurationManager获取信息
//The null in OpenWebConfiguration(null) specifies that the standard web.config should be opened
System.Configuration.Configuration root = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
var httpRuntime = root.GetSection("system.web/httpRuntime") as System.Web.Configuration.HttpRuntimeSection;
int maxRequestLength = httpRuntime.MaxRequestLength;
原则上你应该能够对<requestLimits maxAllowedContentLength="" /> 做同样的事情。但是 WebConfigurationManager 中的system.webServer-Section 被声明为 IgnoreSection 并且无法访问。可以在 application.config 或类似的 IIS 中更改此行为。但是由于(在我的情况下)即使.SectionInformation.GetRawXml() 失败了,我倾向于宣布这是一个失败的案例。
在这种情况下,我的解决方案是手动访问 Web.config-File:
var webConfigFilePath = String.Format(@"{0}Web.config", HostingEnvironment.MapPath("~"));
XDocument xml = XDocument.Load(System.IO.File.OpenRead(webConfigFilePath));
string maxAllowedContentLength = xml.Root
.Elements("system.webServer").First()
.Elements("security").First()
.Elements("requestFiltering").First()
.Elements("requestLimits").First()
.Attributes("maxAllowedContentLength").First().Value;
@Roman here 使用 Microsoft.Web.Administration.ServerManager 提出了另一个解决方案,您需要 Microsoft.Web.Administration Package
【讨论】: