5

I need to access the system.webServer/security/requestFiltering/requestLimits section from the web.config file, to get the value of the attribute maxAllowedContentLength. This value is needed to validate a configuration, so the user can't set a higher value than the value defined inside the web.config file. To validate this configuration, the value from the attribute maxRequestLength (system.web/httpRuntime) is also needed, but we are already getting that value by the code below:

(ConfigurationManager.GetSection("system.web/httpRuntime") as System.Web.Configuration.HttpRuntimeSection).MaxRequestLength

I've already tried:

  • (ConfigurationManager.GetSection("system.webServer") as IgnoreSection).SectionInformation.GetRawXml(), but it throws a System.InvalidOperationException.

  • (System.Web.Configuration.WebConfigurationManager.GetSection("system.webServer") as IgnoreSection).SectionInformation.GetRawXml(), but it also throws a System.InvalidOperationException.

  • ConfigurationManager.GetSection("system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength"), but it returns null.

  • System.Web.Configuration.WebConfigurationManager.GetSection("system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength"), but it also returns null.

  • ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) as suggested by DiskJunky, but it throws a System.ArgumentException, with the message "exePath must be specified when not running inside a stand alone exe".

Also, I made the code below:

using (System.IO.StreamReader reader = new System.IO.StreamReader(System.Web.HttpRuntime.AppDomainAppPath + "/web.config"))
{
    System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
    xmlDocument.LoadXml(reader.ReadToEnd());

    if (xmlDocument.GetElementsByTagName("requestLimits").Count > 0)
    {
        var attrMaxAllowedContentLength = xmlDocument.GetElementsByTagName("requestLimits")[0].Attributes.Cast<System.Xml.XmlAttribute>().FirstOrDefault(atributo => atributo.Name.Equals("maxAllowedContentLength"));
        return (Convert.ToDecimal(attrMaxAllowedContentLength.Value) / (decimal)(Math.Pow(1024, 2)));
    }

    //Default value of the configuration
    return (decimal)28.6;
}

But I tought it was not the best solution.

P.S.: I'm working with the possibility that the value from maxRequestLength and maxAllowedContentLength may differ.

P.S.2.: I know about the Microsoft.Web.Administration, but I need a solution that doesn't involve this dll.

  • 1
    Possible duplicate of [Get maxRequestLength value from specific location path in config](https://stackoverflow.com/questions/34093968/get-maxrequestlength-value-from-specific-location-path-in-config) – DiskJunky Oct 03 '17 at 13:39

2 Answers2

5

My Answer is that your final conclusion is correct.

I could find nothing better. I wrapped up your answer with a few tweaks and included the ability to correctly get the [MaxRequestLength] as Bytes. I then do a Math.Min on both values to let my users know that the actual limit is the lower of the two settings.

    /// <summary>
    /// Get [maxAllowedContentLength] from web.config
    /// </summary>
    internal static long GetMaxAllowedContentLengthBytes()
    {
        const long DefaultAllowedContentLengthBytes = 30000000;
        using (System.IO.StreamReader reader = new System.IO.StreamReader(System.Web.HttpRuntime.AppDomainAppPath + "/web.config"))
        {
            System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
            xmlDocument.LoadXml(reader.ReadToEnd());

             if (xmlDocument.GetElementsByTagName("requestLimits").Count > 0)
            {
                var maxAllowedContentLength = xmlDocument.GetElementsByTagName("requestLimits")[0].Attributes.Cast<System.Xml.XmlAttribute>().FirstOrDefault(atributo => atributo.Name.Equals("maxAllowedContentLength"));
                return Convert.ToInt64(maxAllowedContentLength.Value);
            }
            else
                return DefaultAllowedContentLengthBytes;
        }
    }

    /// <summary>
    /// Get [MaxRequestLength] from web.config
    /// </summary>
    internal static long GetMaxRequestLengthBytes()
    {
        return (HttpContext.Current.GetSection("system.web/httpRuntime") as System.Web.Configuration.HttpRuntimeSection).MaxRequestLength * 1024;
    }
AnthonyVO
  • 3,821
  • 1
  • 36
  • 41
0

That answer has a dependency on the setting existing in the web.config. You either have to put in multiple If statements to deal with non-existent tags or handle the errors thrown. What I needed was a way to get the number even if it was set in the IIS and not in the web.config. I used the solution recommended by Microsoft here (see code at bottom of page)

Here's what I did in VB

Private Function GetmaxAllowedContentLength() As Nullable(Of Int64)
    Dim serverManager As ServerManager = New ServerManager
    Dim config As Configuration = serverManager.GetWebConfiguration(GetExecutingAssembly.GetName.Name)
    Dim requestFilteringSection As ConfigurationSection = config.GetSection("system.webServer/security/requestFiltering")
    Dim requestLimitsElement As ConfigurationElement = requestFilteringSection.GetChildElement("requestLimits")
    Dim value As Nullable(Of Int64) = requestLimitsElement.Item("maxAllowedContentLength")

    Return value
End Function