How to read system value from web.config and use in ASP.NET MVC C# method

zuallauz picture zuallauz · Jan 10, 2013 · Viewed 18.4k times · Source

I'm working on a ASP.NET MVC3 web application (not written by me) which has a max upload size of 100MB. Now this web application gets installed on server machines for customers so it would be nice if this value max upload size was configurable for each customer. They have access to edit the web.config for the web application if need be.

Now there's a value in the web.config like so:

<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="104857600" />
        </requestFiltering>
    </security>
</system.webServer>

Also there's another value here which appears to be similar:

<system.web>
    <httpRuntime maxRequestLength="104857600" executionTimeout="360" />
</system.web>

That 104857600 bytes appears to be the 100MB file upload limit. However on changing the value I discovered that this isn't the authoritative value and it wasn't obeying the new limit. So after some more digging I found somewhere else in the C# code was a hardcoded value public const double MaxContentSize = 104857600 and another C# method was using that value to accept/deny the Ajax file upload.

So what I think I'd like to do is replace that hard coded number in the code so it reads from the value in the web.config. Then at least anyone can change that value in the web.config when they deploy the website.

Can you do something like this?

MaxContentSize = ConfigurationManager.systemWeb.httpRuntime['maxRequestLength'];

I've seen some examples using appSettings in the web.config e.g.

<appSettings><add key="MySetting" value="104857600" /></appSettings>

then accessing it like:

ConfigurationManager.AppSettings["MySetting"]

But that would mean adding a custom value in there and now we'd have 3 places to change it in the web.config. Anyone got an idea how to do it properly?

Many thanks

Answer

Justin Skiles picture Justin Skiles · Jan 10, 2013

You can do something like:

int maxRequestLength = 0;
HttpRuntimeSection section =
ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
if (section != null) 
    maxRequestLength = section.MaxRequestLength;