Wrox Programmer Forums
|
BOOK: Beginning ASP.NET Web Pages with WebMatrix
This is the forum to discuss the Wrox book Beginning ASP.NET Web Pages with WebMatrix by Mike Brind, Imar Spaanjaars ; ISBN: 978-1-1180-5048-4
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Beginning ASP.NET Web Pages with WebMatrix section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old June 2nd, 2012, 03:02 PM
Registered User
 
Join Date: May 2012
Posts: 14
Thanks: 3
Thanked 1 Time in 1 Post
Default _PageStart.cshtml is not handing exception

I'm on page 226 of the book and I'm puzzled by what's happening when I try to upload a file larger than 4MB.

I did everything exactly as show on page 222, and the code worked as expected. But when I modified the code to use _PageStart.cshtml, all hell broke loose! Instead of getting a nice error page describing the error that was thrown, I'm getting the usual error page that IIS7 displays. What am I missing?

Here are the steps I've gone through to run the site:
  1. Select and run Default.cshtml.
  2. Choose a file larger than 4MB.
  3. Click Upload button and wait.
  4. Result: Standard IIS7 error page.

Quote:
HTTP Error 404.13 - Not Found
The request filtering module is configured to deny a request that exceeds the request content length.

Most likely causes:
Request filtering is configured on the Web server to deny the request because the content length exceeds the configured value.

Things you can try:
Verify the configuration/system.webServer/security/requestFiltering/requestLimits@maxAllowedContentLength setting in the applicationhost.config or web.config file.

Detailed Error Information:
Module RequestFilteringModule
Notification BeginRequest
Handler cshtml-Integrated-4.0
Error Code 0x00000000
Requested URL http://localhost:30844/Default.cshtml
Physical Path C:\Documents and Settings\Darel Johnson\My Documents\My Web Sites\Chapter 9\Default.cshtml
Logon Method Not yet determined
Logon User Not yet determined
Request Tracing Directory C:\Documents and Settings\Darel Johnson\My Documents\IISExpress\TraceLogFiles\CHAPTER 9

More Information:
This is a security feature. Do not change this feature unless the scope of the change is fully understood. You can configure the IIS server to reject requests whose content length is greater than a specified value. If the request's content length is greater than the configured length, this error is returned. If the content length requires an increase, modify the configuration/system.webServer/security/requestFiltering/requestLimits@maxAllowedContentLength setting.
View more information »
This error page is not what I'm expecting to see. I was under the impression that I would be able to redirect to Error.cshtml. But that doesn't happen.

web.config
HTML Code:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- Custom Errors -->
  <system.web>
        <compilation debug="false" targetFramework="4.0" />
        <!-- This is commented out
        <customErrors mode="Off" >
            <error statusCode="404" redirect="404.cshtml" />
        </customErrors>
        -->
  </system.web>
  <!-- Email -->
  <system.net>
        <mailSettings>
            <smtp deliveryMethod="SpecifiedPickupDirectory">
                <specifiedPickupDirectory pickupDirectoryLocation="C:\Mail\" />
            </smtp>
        </mailSettings>
  </system.net>
  
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebMatrix.WebData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebMatrix.Data" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
Default.cshtml
HTML Code:
@{
    /* test Exception handling */
    //throw new NullReferenceException();
    
    var message = "";
    try{
        if(Request.Files.Count > 0 ){
            WebImage image = WebImage.GetImageFromRequest();
            if(image != null){
                message = "Upload succeeded";
            } else {
                message = "You must upload an image file: .jpg, .gif, .png, .bmp, .tif";
            }
        }
    }
    catch(Exception ex){
        message = "Upload unsuccessful because: " + ex.Message;
    }
    
}
<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <h1>Upload Images</h1>
        <div>@message</div><br/>
        @FileUpload.GetHtml(allowMoreFilesToBeAdded: false)
    </body>
</html>
_PageStart.cshtml
HTML Code:
@{
    /// Catch any errors in Webpages in the same folder or subfolder
    /// and report errors via email
    try{
        RunPage();
    } 
    catch(Exception ex){
        var message = ex.Message + "\n";
        var stack   = ex.StackTrace;
        
        var logEntry = DateTime.Now + "\n" + message + stack;
        logEntry += "\n===============================\n";
        var location = Server.MapPath("~/App_Data");
        var fileName = "errorlog.txt";
        var path = Path.Combine(location, fileName);
        
        File.AppendAllText(path, logEntry);
        WebMail.Send(
            to: "djohnson@domain.com", 
            subject: "Error on site: ", 
            body: "The following error occurred\n" + message + stack, 
            isBodyHtml: false
        );
        
        Response.Redirect("~/Error/");
      
    }
    
}
Error.cshtml
HTML Code:
<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Error Report Page</title>
    </head>
    <body>
        <h1><span style="color:Orange"><em>Oops!</em></span> An error occurred</h1>
        
    </body>
</html>
 
Old June 3rd, 2012, 07:03 AM
Wrox Author
 
Join Date: Dec 2011
Posts: 57
Thanks: 1
Thanked 19 Times in 19 Posts
Default

If your upload exceeds 27MB, IIS request filtering kicks in before ASP.NET even gets a chance to object. See step 5 on p. 223.
The Following User Says Thank You to Mike Brind For This Useful Post:
dejohnny (June 3rd, 2012)
 
Old June 3rd, 2012, 08:30 PM
Registered User
 
Join Date: May 2012
Posts: 14
Thanks: 3
Thanked 1 Time in 1 Post
Cool Do I need to perform sanity checks on file before uploads?

It looks like I would need to perform a sanity check on any file that gets uploaded then.

We could use the Request object property TotalBytes, to check for the size of the HttpRequest before it gets uploaded.

Also, in this instance, I will not be using _PageStart.cshtml to trap errors from web pages. It doesn't work as expected. I think it's better to handle exceptions on each page individually and then send the errors by calling one function that takes care of logging and emailing.

Solution
Code:
@{
    var pageTitle = "Default Page";
    var message = "";
    
    try{
        /// upload the image, if the byte stream 
        /// is less than 3MB
        if(Request.TotalBytes < 3145728  ){ 
            if(Request.Files.Count > 0 ){
                /// WebImage class only understands the 
                /// properties of binary images
                WebImage image = WebImage.GetImageFromRequest();
                    if(image != null){
                        message = "Upload succeeded";
                    } else {
                        message = "You must upload an image file: .jpg, .gif, .png, .bmp, .tif";
                    }    
			}
        } 
        else {
			message = "You cannot upload files larger than 3MB!";
		}
    }
    catch(Exception ex){
        message = "Upload unsuccessful because: " + ex.Message;
        /// Log errors and send email notifications when errors occur
        Functions.debugNotify( ex, message, pageTitle);
    }
    
}
The only problem with this approach is that, WebImage objects only detect the properties of binary filestreams. This will not work, if for example, you accidentally upload a PDF or exe file. IIS7 will baulk at you with a 404.13 error page if you do that.





Similar Threads
Thread Thread Starter Forum Replies Last Post
sell.cshtml hozdaman BOOK: Beginning ASP.NET Web Pages with WebMatrix 2 May 9th, 2012 09:42 AM
book for cshtml lizanta ASP.NET 4 General Discussion 0 January 31st, 2012 02:31 AM
Chapter 4 Testing _PageStart.cshtml jpjamie BOOK: Beginning ASP.NET Web Pages with WebMatrix 2 January 5th, 2012 03:32 AM
Better way of handing paging HPro ASP.NET 2.0 Professional 1 April 16th, 2008 12:54 PM
Handing Errors groupmatch BOOK: ASP.NET Website Programming Problem-Design-Solution 1 October 2nd, 2004 01:47 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.