如何读取maxAllowedContentLength

4

我有一个用于上传文件的Flash组件,希望在客户端处理最大文件大小限制,而不实际将文件发送到服务器。因此,我需要以某种方式从配置文件中读取该值以发送给客户端。我找到的一些文章说直接读取配置文件并不是解决方案,因为它可能会在很多地方被更改。因此,可能应该有一些API调用,但我找不到任何相关的信息...

<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="1048576" />
        </requestFiltering>
    </security>
</system.webServer>
3个回答

7

我知道这是一个老问题,但花费了我很多时间(浪费),因此我觉得为那些可能会遇到同样问题的人发布一个可行的解决方案:

Using Microsoft.Web.Administration;

uint uiMaxAllowedContentLength = 0;
using (ServerManager serverManager = new ServerManager())
{
    Configuration config = serverManager.GetWebConfiguration("Default Web Site/{{your special site}}");
    ConfigurationSection requestFilteringSection = config.GetSection("system.webServer/security/requestFiltering");
    ConfigurationElement requestLimitsElement = requestFilteringSection.GetChildElement("requestLimits");
    object maxAllowedContentLength = requestLimitsElement.GetAttributeValue("maxAllowedContentLength");
    if (null != maxAllowedContentLength)
    {
        uint.TryParse(maxAllowedContentLength.ToString(), out uiMaxAllowedContentLength);
    }

}

请确保首先下载并安装Microsoft Web Administration包(

PM> Install-package Microsoft.Web.Administration

此外,您可能需要调整对您的web.config文件的权限。为IUSR和IIS_IUSRS授予至少“读取”权限。

这段代码实际上来自Microsoft网站,但是要找到它花费了很长时间!希望我为您节省了几个小时。

干杯,

Roman


1

没有 Microsoft Web Administration 包:

using System.Web.Configuration;
using System.Configuration;
using System.Xml;
using System.IO;

Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
IgnoreSection ignoreSection = configuration.GetSection("system.webServer") as IgnoreSection;
string sectionXml = ignoreSection.SectionInformation.GetRawXml();
StringReader stringReader = new StringReader(sectionXml);
XmlTextReader xmlTextReader = new XmlTextReader(stringReader);
UInt32 maxAllowedContentLength = 0;
if(xmlTextReader.ReadToDescendant("requestLimits"))
    UInt32.TryParse(xmlTextReader.GetAttribute("maxAllowedContentLength"), out maxAllowedContentLength);

0

试试这个方法

您可以根据配置文件中的 Web 配置更改下面的代码段。

我的 web.config 可能如下所示

<system.web>
  <httpRuntime executionTimeout="30"  maxRequestLength="100"/>

在这里,您可以看到maxRequestLength被定义为100,可以从代码后台更改

添加using System.Web.Configuration;

现在编写此代码以更改maxRequestLength的值

Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
HttpRuntimeSection httpruntinesec =
    (HttpRuntimeSection)configuration.GetSection("system.web/httpRuntime");

您可以使用httpruntinesce实例来设置值。


6
我不确定是否应该对此回答进行负评,因为它是读取 system.web/httpRuntime 中的 "maxRequestLength" 而不是 system.webServer/security/requestFiltering/requestLimits 中的 "maxAllowedContentLength"。 - user57508
1
我认为这是可以的,因为我们可以将两个设置(maxRequestLength和maxAllowedContentLength)都设置为相应的(相同的)值,并且只使用此代码,跳过安装“Microsoft.Web.Administration”包。 - Motlicek Petr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接