title: Displaying Message if file size exceeds max limit
body: <p>I'm developing a website in Asp.Net and one of the page requires users to upload files. The client wants the file size limit to be set to 5MB max. I have set the limit in the <code>web.config</code> using the following code; </p>
  
  <pre><code> &lt;system.webServer&gt;
  &lt;security&gt;
    &lt;requestFiltering&gt;
      &lt;requestLimits maxAllowedContentLength="5242880" /&gt; &lt;!--5MB--&gt;
    &lt;/requestFiltering&gt;
  &lt;/security&gt; &lt;/system.webServer&gt;
  </code></pre>
  
  <p>The C# code for the page to check the file extension and display the error message to the users has the following code.</p>
  
  <pre><code>string[] validFileTypes = { "doc", "docx", "xls", "pdf" };
      string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
      bool isValidFile = false;
  
      for (int i = 0; i &lt; validFileTypes.Length; i++)
      {
          if (ext == "." + validFileTypes[i])
          {
              isValidFile = true;
              break;
          }
      }
          if (!isValidFile)
          {
              DisplayMessage.Visible = true;
              DisplayMessage.Text = "Invalid file or file size has exceeded it max limit of 5MB. Please upload a file with one of the following extension; &lt;br /&gt;&lt;br /&gt;" +
              string.Join(", ", validFileTypes) + "or a smaller file";
      }
      else
      {
          string targetFolder = HttpContext.Current.Server.MapPath("~/App_Data/");
          string targetPath = Path.Combine(targetFolder, FileUpload1.FileName);
          FileUpload1.SaveAs(targetPath);
  
          DisplayMessage.Visible = true;
          DisplayMessage.Text = "File uploaded successfully.";
      }
  </code></pre>
  
  <p>The issue I am having is when I try to upload a file which is bigger than 5MB instead of the page displaying the error message it throws me a <code>stack trace</code> <img src="https://i.stack.imgur.com/xKv71.png" alt="enter image description here"> </p>
  
  <p>Can someone please tell me where I'm going wrong. Many Thanks in advance!</p>