Link to home
Start Free TrialLog in
Avatar of davidclark73
davidclark73

asked on

ASP.NET Application_Error Response.Redirect

Is it actually possible to do a response.redirect from inside Application_Error?

I have called Server.ClearError()
then i do a Response.Redirect("whatveraddress", False)

and it does nothing, i just get the same "The page cannot be displayed" error.


thanks
Avatar of Slimshaneey
Slimshaneey
Flag of United Kingdom of Great Britain and Northern Ireland image

Avatar of davidclark73
davidclark73

ASKER

not really no. I know how to use response.redirect

the problem is it is not working in my application_error handler
Response.Redirect("whatveraddress.aspx", False)

Was that typo or did you forget the .aspx in the code?
Unless you have a "on error resume next" the clearerror etc won't be processed because without this execution stops.

However even if you do put this in there are still some errors that will prevent execution from continuing (ASP 147 for example which is lack of resources).

If all you is trying to do is present you own 'pretty' error page the better (and proper way) is to create your own error pages and configure IIS to use these.

HTH
Steve

Whoops didn't see we were .Neting!
Yes, need this for customs:

<configuration>
<system.web>
<customErrors defaultRedirect="default.aspx" mode="RemoteOnly">
<error statusCode="404" redirect="customerror.aspx"/>
</customErrors>
</system.web>
</configuration>
not a typo - what i mean is it doesn't matter where i try to redirect to. "error.aspx" "www.hotmail.com" "http://www.hotmail.com" anything

the error that i am trying to trap is actually the error generated by an upload being more than the maxRequestLength setting (this is a System.Web.HttpException with its ErrorCode set to -2147467259) do you think i can configure a customErrors page for that?

I have traced the code into application_error after generating the error by uploading a large file and all the code works, the response.redirect is called and does not throw another exception. It just does not do what I expect - actually redirect to the new page. (i actually want the browser to go back to the submitting page and display an error that says the file is too large)
You should encapsulate the UPLOAD code in a TRY statement.  The TRY will catch the error:

Try
  'upload code
Catch ex as Exception
  'do what you need to do when error happens
Finally
  'close any connections
End Try

yeah the thing it this type of error occurs before the code, it is very early in the request handling - at form submittal.
argh geez, look im sorry i dont want to be bitchy but i know how to code - it is an application level exception - it is not coming from server code it is coming direct from the application - before the post from the client is even finished (that is the point basically, it is to stop people from uploading large files if you dont want them to - if it wasnt an exception thrown so early the file would have already been read into the server memory)

i really think that it is aproblem of the response object not even being totally populated yet that is why i was wanting someone with an answer rather than links to ASP101 tutorials.

thanks anyway.
i guess this is a harder question than i though - i am going to add some more points...
What is the stack trace?
the stack trace is:

   at System.Web.HttpRequest.GetEntireRawContent()
   at System.Web.HttpRequest.GetMultipartContent()
   at System.Web.HttpRequest.FillInFormCollection()
   at System.Web.HttpRequest.get_Form()
   at System.Web.UI.Page.GetCollectionBasedOnMethod()
   at System.Web.UI.Page.DeterminePostBackMode()
   at System.Web.UI.Page.ProcessRequestMain()
I meant the whole error page, sorry.  The actual stack trace is pretty useless!

Nevermind...
its not giving an ASP.NET error actually. just a html "error" page.
the page that i get with or without a redirection is the same. As soon as the size of the file uploaded exceeds the maximum the page the browser displays is this one (instead of calling my aspx)

- its not really the sort of page that you want to pop up in your application just because the max filesize is exeeded, but unless i can find some way to do something in application_error...

infact, netscape does something different... still no redirect, but it goes to try to fetch some keyword or something from netscape.com (and fails) with an error "The operation timed out when attempting to contact keyword.netscape.com". Then the page stays at the original aspx page - which is bettter than ie's effort i suppose...

[the source of the page, fwiw]:

<head>
<style>
a:link                  {font:8pt/11pt verdana; color:red}
a:visited            {font:8pt/11pt verdana; color:#4e4e4e}
</style>
<meta HTTP-EQUIV="Content-Type" Content="text-html; charset=Windows-1252">
<title>Cannot find server</title>
</head>

<SCRIPT>

      function doNetDetect() {
        saOC.NETDetectNextNavigate();
            document.execCommand('refresh');
            }

function initPage()
{
    document.body.insertAdjacentHTML("afterBegin","<object id=saOC CLASSID='clsid:B45FF030-4447-11D2-85DE-00C04FA35C89' HEIGHT=0 width=0></object>");
}

</SCRIPT>

<body bgcolor="white" onload="initPage()">

<table width="400" cellpadding="3" cellspacing="5">
  <tr>
    <td id="tableProps" valign="top" align="left"><img id="pagerrorImg" SRC="pagerror.gif"
    width="25" height="33"></td>
    <td id="tableProps2" align="left" valign="middle" width="360"><h1 id="textSection1"
    style="COLOR: black; FONT: 13pt/15pt verdana"><span id="errorText">The page cannot be displayed</span></h1>
    </td>
  </tr>
  <tr>
    <td id="tablePropsWidth" width="400" colspan="2"><font
    style="COLOR: black; FONT: 8pt/11pt verdana">The page you are looking for is currently
    unavailable. The Web site might be experiencing technical difficulties, or you may need to
    adjust your browser settings.</font></td>
  </tr>
  <tr>
    <td id="tablePropsWidth" width="400" colspan="2"><font id="LID1"
    style="COLOR: black; FONT: 8pt/11pt verdana"><hr color="#C0C0C0" noshade>
    <p id="LID2">Please try the following:</p><ul>
      <li id="instructionsText1">Click the
      <a xhref="javascript:location.reload()" target="_self">
      <img border=0 src="refresh.gif" width="13" height="16"
        alt="refresh.gif (82 bytes)" align="middle"></a> <a xhref="javascript:location.reload()" target="_self">Refresh</a> button, or try again later.<br>
      </li>
     
      <li id="instructionsText2">If you typed the page address in the Address bar, make sure that
        it is spelled correctly.<br>
      </li>
      <li id="instructionsText3">To check your connection settings, click the <b>Tools</b> menu, and then click
        <b>Internet Options</b>. On the <b>Connections</b> tab, click <b>Settings</b>.
        The settings should match those provided by your local area network (LAN) administrator or Internet service provider (ISP). </li>
     <li ID="list4">If your Network Administrator has enabled it, Microsoft Windows
         can examine your network and automatically discover network connection settings.<BR>
         If you would like Windows to try and discover them,
         <br>click <a  href="javascript:doNetDetect()" title="Detect Settings"><img border=0 src="search.gif" width="16" height="16" alt="Detect Settings" align="center"> Detect Network Settings</a>
      </li>
    <li id="instructionsText5">
       Some sites require 128-bit connection security. Click the <b>Help</b> menu and then click <b> About Internet Explorer </b> to determine what strength security you have installed.
    </li>
    <li id="instructionsText4">
       If you are trying to reach a secure site, make sure your Security settings can support it. Click the <B>Tools</b> menu, and then click <b>Internet Options</b>.  On the Advanced tab, scroll to the Security section and check settings for SSL 2.0, SSL 3.0, TLS 1.0, PCT 1.0.
    </li>
     <li id="list3">Click the <a href="javascript:history.back(1)"><img valign=bottom border=0 src="back.gif"> Back</a> button to try another link. </li>    
     
     
    </ul>
    <p><br>
    </p>
    <h2 id="IEText" style="font:8pt/11pt verdana; color:black">Cannot find server or DNS Error<BR> Internet Explorer
      
    </h2>
    </font></td>
  </tr>
</table>
</body>
</html>
Have you tried to change the request length?  

<configuration>
<system.web>
<httpRuntime maxRequestLength="4000"/>
</system.web>
</configuration>

I want there to be a maximum. It is when the maximum is hit that I want to show a message. I don't wish to allow files of any old size, I just want to be able to trap and respond to the error when it occurs.
Yeah, I figured that...but can't seem to find much on handling of this error...
me neither - heheh
it's not looking like you can actually handle it...
You need to incorporate:

<httpRuntime useFullyQualifiedRedirectUrl="true|false"
  maxRequestLength="size in kbytes"
  executionTimeout="seconds"
  minFreeThreads="number of threads"
  minFreeLocalRequestFreeThreads="number of threads"
  appRequestQueueLimit="number of requests" />

And then set up custom errors to handle when this parameter is not met....

<customErrors defaultRedirect="genericerror.htm" mode="RemoteOnly">
  <error statusCode="500" redirect="InternalError.htm"/>
</customErrors>


See here for info:

http://www.dotnetjohn.com/articles/articleid24.aspx
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/gngrfhttpruntimesection.asp
I had thought of that, but couldn't find any information on what statusCode would be for this type of error. I don't want to redirect every error either.
Isn't the status code show in the Browser Title?

And you don't have to redirect for all, just the status code you specify.
nope, just says "Cannot find server - Microsoft Internet Explorer"

very frustrating.
Geez...how bout if you increase the upload size as shown above in config, then check the files size in the code and if it is too big, redirect to page you want.
ASKER CERTIFIED SOLUTION
Avatar of alorentz
alorentz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
See here for checking file size with .contentlength properties:

http://www.4guysfromrolla.com/webtech/091201-1.shtml
The content lenght stuff is after the exeption is thrown.

I was hoping not to find something like the M$ article that you found... damn.

I guess I could set the filesize to much larger and then i could generate a message for most files that are too big... only if the file is much too big there is still the nasty page...
Plus the file will have already been uploaded by then... We want to allow up to 100Mb, so a reasonable leeway would be 50-100% more... The user would be going "WTF%$?$%?%% i just waited 10 minutes for my file to upload and NOW you tell me its too ///$$%?$%?%$? big???!!" heheh. i like the thought of that... but nawww.

I think i will formulate my question a bit better in light of this new information and see if anyone has any ideas on how to workaround this problem..

but thanks for trying... i am going to mark your answer with the M$ article as the answer --- just one of those times i guess when "you can't... mostly" is the correct response.

thanks again.
the appropriate section from the MS site incase anyone stumbles over this Q sometime...

--

By default, ASP.NET only permits files that are 4,096 kilobytes (KB) (or 4 MB) or less to be uploaded to the Web server. To upload larger files, you must change the maxRequestLength parameter of the <httpRuntime> section in the Web.config file.

Note When the maxRequestLength attribute is set in the Machine.config file and then a request is posted (for example, a file upload) that exceeds the value of maxRequestLength, a custom error page cannot be displayed. Instead, Microsoft Internet Explorer will display a "Cannot find server or DNS" error message.
I'm facing the same problem. Can you tell me how do you manage to solve the problem? Thanks in advance.
I didn't. You can't show any custom error page. You have to live with the "Cannot find server or DNS" message from M$ and the "The operation timed out [...]" message from Netscape.
I've tried a number of solutions to solve this problem and your right; there is no way to overcome it. I even tried to retrieve the contentlength of the request object and manage files that are too large through an HTTPModule. I 've tried using the Application BeginRequest event which is fired when the server first responds to a request from the client.

However, as far as I can tell, the upload is denied before this event is even fired (ie. the upload is denied before you can do anything about it), and I don't know if it is possible to handle anything in ASP.NET code before Application_BeginRequest. The only thing I can think of is if you intercept the request before it gets the the ASP.NET engine (but I wouldn't know where to begin with such functionality).

Unfortunately, file uploads are a main feature of my site and I have had to start looking for another language that allows better handling of such a feature.
The error is thrown in the way it is because within HTTP nothing is normally done until the complete message is received. By setting a limit .Net is breaking the normal run of things and the message is incomplete. However this has been done to prevent denial of service attacks (where someone uploads a huge file in the hope of killing the server either by running it out of memory, filling up disk space or just keeping it too busy).
So the trick with this setting is to set the maximum value in the web.config to a higher value than you are looking to allow to upload as a safe guard and then trap those that upload a file smaller than this but higher than your personal limit within your code. This way you can handle those who have accidentally sent too bigger file gracefully and those who are doing something dubious or stupid (like uploading a 100mb passport photo as one of my users tried to!) can suffer the less graceful error.

HTH
Steve
Yeah, I do have links to two library solutions to the problem - i guess that they "go in before the request is sent to the asp engine"

and for the price (Free (as in beer - Creative Commons) and 149$ US) they sound like damn fine value

- HTTP Upload Manager (http://krystalware.com/wiki/default.aspx/KrystalWiki.HttpUploadManager)
- ABCUpload (http://www.websupergoo.com/products.htm#up)

as for the "watermark solution" i guess that is a good one for a site that wants to accept say 5Mb images - you set you soft limit to 5 and your hard limit to 50 or 100, take the 100Mb hit if someone posts their passport photo and the rest who forgot to turn on JPG compression get your nice message... But me - i am writing an intranet document management site - It needs to accept up to about 500Mb files - if i even give a leeway of a couple hundred megs the upload could still take 5 or so minutes before it failes due to "sorry you file is too big - tee hee".

anyway. i would try the upload manager and then if that is not satisfactory (or the licencing doesn't work out for you) the ABCgooeywebbythingy.