Response.write in application_error not working? - c#

Ok, I have a weird problem and can't find anything about it online. I'm trying to get custom application-level error handling working in ASP.NET. I have customErrors turned off in the web.config with the hopes of handling everything in application_error. Bear with me...
My code in global.asax is very simple:
void Application_Error(Object sender, EventArgs e) {
HttpContext.Current.Trace.Write("ERROR MESSAGE");
Response.TrySkipIisCustomErrors = true;
var error = Server.GetLastError();
HttpContext.Current.Response.Write("ERROR MESSAGE");
HttpContext.Current.ClearError();
}
I created a simple aspx page and threw an error in Page_Init or Page_Load, and everything worked as expected, i.e.: I see "ERROR MESSAGE" on a blank page when an error occurs.
Now I dynamically add some user controls to that aspx page and everything renders as expected. If I then throw an error from INSIDE one of the controls, I only get a blank white page. "ERROR MESSAGE" does not appear.
Now I know that application_error is still firing because when I remove the call to ClearError(), I get a Yellow Screen Of Death. Also, I can execute a Server.Transfer in there and that works fine. But nothing will come out for Response.Write.
This goes further: I can set Response.StatusCode, but a Response.Redirect will error out (and thus throw me into an infinite loop). Trying to write to the Event Log also errors out, but instead of throwing a new error, it throws the original, i.e.: "Input string was not in a correct format." when I try to convert a string to a number. As mentioned, Response.Write doesn't do anything, though it does not throw an error.
So looking at my trace log, in the second case (exception inside dynamically added user control) I see a full control tree and the error occurs right after Begin Render. In the first case, the tree is empty and the error is thrown either after Init or Load. Both times, trace.axd reports Unhandled Execution Error.
When I move the throw inside the control to the control's constructor or OnInit, things work as expected. When I move it to OnLoad or Render, it gets goofy.
So I'm wondering if at some point the Response object loses certain functionality. I've tried all sorts of permutations, from syntax (using HttpContext.Current.Response vs Context.Response vs pulling the Response object from the "sender" parameter), to moving the ClearError() or Response.Clear(), etc methods around, etc. I've tested the Response object for "null-ness" as well, and it never reports a null. I can set some response properties (http status code) but not others.
I'm using IIS7.5 integrated mode (.NET v4), but experienced similar problems when I tried Classic mode.
So I'm trying to solve this mystery, obviously, but my goal is to ultimately handle all errors, no matter what point in the asp.net lifecycle they occur, and to be able to write out some information from the handler (ie application_error).

Handled unhandled exceptions using this approach. Custom error is off in web.config.
All 3 options work.
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Response.TrySkipIisCustomErrors = true;
this.Server.ClearError();
this.Server.GetLastError();
//DO SOMETHING WITH GetLastError() may be redirect to different pages based on type of error
//Option 1:
Response.Write("Error");
//Option 2:
Response.Redirect("~/Error.aspx");
//Option 3:
this.Server.Transfer("~/Error.aspx");
}

Related

Turn off HttpRequestValidationException logging?

We have an exception that keeps cropping up in our Event Viewer logs for our server, caused by explicit attempts to hack our site by our PCI security company. It gets annoying as it crops up all the time, and initially it was generating the 'yellow screen of death' and logging in the event viewer as an unhandled exception. We put an exception handler around the code where he exception was coming from (inside Phalanger if you are interested), so it now longer crashes and causes the yellow screen of death, but it STILL ends up in the event viewer logs as a warning!
Any idea how to turn it off in the event viewer short of turning off request validation completely, which I was trying to avoid?
We are using ASP.NET MVC 3 so I know I can use the new ValidateInput attribute to do this, but I would rather leave it turned on but be able to handle the exceptions ourselves and not have them get logged to the event viewer even though I catch it and handle it?
Add following code to Global.asax.cs
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex is HttpRequestValidationException)
{
Server.ClearError();
Response.Clear();
Response.StatusCode = 200;
// add content below
Response.Write("");
Response.End();
}
}

How to handle ReportViewerWebPart report printing error?

I’m implementing a solution based on SharePoint 2010 and MS Reporting Server. I’m experiencing a problem with ReportViewerWepPart. I have a scenario where I need to display a custom error when a report cannot be printed. Unfortunately, unlike ReportViewer asp control, ReportViewerWepPart does not have any properties/events indicating that there is an error and the report cannot be printed. After spending some time on the problem I came with a solution using reflection. I discovered that ReportViewerWepPart uses internally ReportViewer and I attached to ReportError event on this private internal component. Here is my code:
…
try
{
ReportViewer rv = (reportViewer.GetType().GetField("m_reportViewer", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(reportViewer) as ReportViewer);
rv.ReportError += new Microsoft.Reporting.WebForms.ReportErrorEventHandler(ReportWidgetControl_ReportError);
}
catch(Exception e)
{
LogHandler.LogError(e, "Unable to attach ReportViewerWebPart error hadler.");
}
…
void ReportWidgetControl_ReportError(object sender, Microsoft.Reporting.WebForms.ReportErrorEventArgs e)
{
reportViewer.Visible = false;
HandleError();
}
Unfortunately this solution is a hack in the web part. Do you think that using a reflection in that way can cause any problems? Am I missing something, Is there another way to see if report is printed?
This is fine, but I would be careful catching all exceptions.
It looks like you are hiding the reportViewer and calling your HandleError code no matter what the error. There may be exceptions that occur that are minor and are handled without issue internally and hiding the reportViewer object might not be appropriate.
I don't know what your HandleError code does but I would suggest quietly logging the error to a log table or file until you spot the exact printing error you are trying to handle, and then only worrying about handling that.

"Callback Error: Invalid response from server" from C# ASP.Net application

I have an ASP.Net application with a button containing the following Javascript to be invoked when it is clicked:-
function calculate() {
sectionIndex = getSelectedRadioIndex("section");
compositionIndex = getSelectedRadioIndex("composition");
CallBackOU.callback( "calculate" , sectionIndex, compositionIndex );
}
I can verify that control reaches the last line of this function by setting a breakpoint on it. But instead of invoking the method in the code-behind file...
protected void CallBackOU_Callback (object sender, ComponentArt.Web.UI.CallBackEventArgs e)
{
//blah blah
}
I get a dialogue reporting
Callback Error: Invalid response from server.
This dialogue appears three times, after which the page sits there doing nothing (forever, so far as I can make out).
I can't find any information about this. Can anyone give me any clues or pointers about how to go about diagnosing the problem?
Without seeing the signature of the calculate callback method this is only a shot in the dark but some issues i have encounter when invoking web methods from javascript are make sure the method is properly decorated [WebMethod], make sure the method is static, make sure the parameters are of the correct type and named properly (they are infact case sensitive when deserializing JSON iirc). A little more information regarding how the call is made (JSON/XML) and the signature might help. Also, you can try using fiddler to see if you get any more information regarding the error.

My Visual Studio 2008 web application keeps throwing a .Net error when I first run it, but refreshing fixes it

As stated in the title my web application builds successfully, although every time I run it in debug mode I get the following .Net error:
If I hit refresh then the application gets no more errors until I next start it up again, any ideas?
Here is my global.asax file:
<%# Application Language="C#" Inherits="MyCompany.Web.MyApp.Shell.CustomWebClientApplication" %>
<script runat="server">
void Session_End(Object Sender, EventArgs e)
{
FormsAuthentication.SignOut();
}
protected void Session_Start(Object sender, EventArgs e)
{
if (Session.IsNewSession)
{
Response.Redirect(System.Web.Configuration.WebConfigurationManager.AppSettings["HomePage"]);
}
}
protected void Application_Error(Object sender, EventArgs e)
{
System.Exception oops = Server.GetLastError();
//Injection attack error handling
if (oops.GetBaseException() is System.Web.HttpRequestValidationException)
{
Response.Redirect("ErrorPage.aspx");
}
}
</script>
You have something which is trying to access a variable which is set to null (or hasn't been initialized). Do you have anything in the Global.asax or anything that fires on the start of the application? Do you have any asynchronous operations that fire on the start of the application?
Check on your Home.aspx page to see what is happening there. It looks like your application redirects to that page, so I would guess that on either the init or page_load event there is something which is executing that it causing the problem.
System.Exception oops
I think that this is source of problems. When there is no object returned from
Server.GetLastError();
then you will get NullReferenceException on line
oops.GetBaseException()
It makes perfect sense. On first run, oops is null (because no error occured before), thus throwing NullReferenceException. On second page refresh, GetLastError() returns object reffering previous errror (NullReferenceException) and page is displayed. Always check objects for null before accessing them.
Anyway, you can always try catching all runtime exceptions (Debug->Exceptions->Common Language runtime) and see where a problem is.
Sounds like an initialization issue. You're probably trying to use a resource before it's initialized, but by the time you refresh it's had time to be initialized.

Catching exceptions within .aspx and .ascx pages

The questions says everything, take this example code:
<ul id="css-id">
<li>
<something:CustomControl ID="SomeThingElse" runat="server" />
<something:OtherCustomControl runat="server" />
</li>
</ul>
Now if an error gets thrown somewhere inside these controlls (that are located in a master page) they will take down the entire site, how would one catch these exceptions?
You can catch all exception not handled elswhere in the Global.asax page / class.
Look at:
protected void Application_Error(Object sender, EventArgs e)
method.
Unfortunately an unhandled exception will always error your site.
YOu can prevent this a few ways though.
Use the section in your web.config to show a user friendly message
In your Global.asax - or a Custom Handler - catch your unhandled exception and react accordingly - like this
best solution
Make sure you controls don't throw unhandled exceptions!
Add a global.asax en implement the Application_Error handler. Use the Server.GetLastError() function to get a handle on the exception thrown.
Using the global.asax Application_Error method, as described in How to create custom error reporting pages in ASP.NET by using Visual C# .NET.
An alternative approach would be to use a HTTP module; this gives you some more flexibility (you can handle errors from multiple applications, for example).
Do you want to catch the exception and handle it?
Or do you want to prevent the Yellow Screen Of Death? If you are trying to prevent the Yellow Screen Of Death, look at handling the Error event on the HttpApplication (in other words, in your Global.asax).
See the following MSDN page for more details:
http://msdn.microsoft.com/en-us/library/system.web.httpapplication.error.aspx
Specifically this paragraph:
The exception that raises the Error event can be accessed by a call to the GetLastError method. If your application generates custom error output, suppress the default error message that is generated by ASP.NET by a call to the ClearError method.

Categories

Resources