Simulating RemoteOnly custom errors using Application_Error ASP.NET - asp.net

I handle my errors using Application_Error in global.asax.
How to check if the request is from the local client to display more information about the error or just show the yellow error page. Something like "remoteOnly" that ASP does when handling errors using web.config.

After I posted the question, I went back to my application and played around a little bit then I found this. Now I'm using it.
void Application_Error(object sender, EventArgs e)
{
if(!HttpContext.Current.Request.IsLocal)
HttpContext.Current.Server.ClearError();
// process error handling
}

Related

ASP.Net Global Error Handling and Error Site?

I am having a huge website with over 100 single sites in ASP.Net.
Of course I try to catch every action with a try-catch block or with other things like validation-controls.
But I want, IF a error happens which I get not catched to happens following:
1) Write the Error in Database
2) Show user a specific site instead the errorsite from asp.net
How to do that?
You can use the Application_Error event handler in in Global.asx to handle any exceptions that are not caught at the page level. See, for example,
http://msdn.microsoft.com/en-us/library/24395wz3(v=vs.100).aspx
It's kind of up to you what you do in the event handler, so you can log the error to a database if you want to. You can also redirect to another page of your choosing to display the error however you want.
Note that the Application_Error event will be raised for all uncaught exceptions, including Http exceptions (e.g. 404 Not found). You probably don't want to log those.
You should try ELMAH
Check out the blog post of Scott Hanselman on how to integrate it in asp.net website and make it work.
Below is the article from Scott Mitchel on how to log errors with Elmah and how to show custom error page to user:
http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/logging-error-details-with-elmah-cs
http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/displaying-a-custom-error-page-cs
If you not into trying elmah, which is a breeze to setup. It depends on how your 100 sites are setup. But you possibly could look into using the global
Application_Error event in global.asax.cs and add you own handling code in there.
protected void Application_Error(object sender, EventArgs e)
{
var lastException = Server.GetLastError();
//log it to db, re-route the request to an alternate location ... etc
}
Another option, again it depends on how your sites are setup/hosted would be to read the event_log on the server, and check for ASP.NET errors saving the relevant details to the db.

HttpContext.current.Session is cleared in error page

I have made a custom error page for my ASP.NET 4 application. I put the exception object in HttpContext.current.Session["CustomError"] but when the user is redirected to the error page HttpContext.current.Session["CustomError"] is null.
I do it in CustomError class constructor like this:
public CustomError(enExceptionType ExceptionType) : base(ExceptionMessage(ExceptionType)) {
HttpContext.Current.Session["CustomError"] = this;
}
when I step over the code Session["Error"] contains the error object.
any idea?
UPDATE:
I removed custom error page from web.config and added this to glabal.asax:
void Application_Error(object sender, EventArgs e)
{
if (Context.IsCustomErrorEnabled)
{
Response.Redirect("~/Error.aspx");
}
}
by stepping through this function I noticed that when an exception is thrown this function is called two time, the first time Session["CustiomError"] contains the error object but the second time its null.
Instead of using Response.redirect(URL) (which I assume you have in your code) use
Server.Transfer(URL)
or
Response.redirect(url, false)
Why Server.Transfer(url)?
Transferring to another page using
Server.Transfer conserves server
resources. Instead of telling the
browser to redirect, it simply changes
the "focus" on the Web server and
transfers the request. This means you
don't get quite as many HTTP requests
coming through, which therefore eases
the pressure on your Web server and
makes your applications run faster.
Source here.
Please let me know if one of these works for you.
UPDATE:
If you use a web config setting can you try adding ResponseWrite value to redirectmode var?
<customErrors mode="RemoteOnly" defaultRedirect="~/errors/GeneralError.aspx" redirectMode="ResponseRewrite" />
If this is still not working I suggest to implement this (I've done it in my application to log the errors in log files (for me as admin) and present a generic error to the user).
This solved the problem, but I would appreciate it if someone tells me why :)
void Application_Error(object sender, EventArgs e)
{
if (Context.IsCustomErrorEnabled)
{
Response.Redirect("~/Error.aspx");
**Server.ClearError();**
}
}

Rediret from global.asax under medium trust

I have this simple Application_Error method in my global.asax, and it does not redirect in case an exception occurs under medium trust. Can someone tell me whats wrong here.
This code works fine under full trust
void Application_Error(object sender, EventArgs e)
{
Response.Redirect("~/error.aspx",false);
}
Apparently removing the false argument fixed this. It does generate a security exception when the redirect executes, but it redirects just fine

global asax application_start application begin_request methods?

I have a problem. While migrating from classic pipeline mode to integrated pipeline mode at IIS 7.0 we encounter the problem :
Server Error in '/' Application.
Request is not available in this context...
We found solution for this problem at
mvolo.com/blogs/serverside/archive/2007/11/10/Integrated-mode-Request-is-not-available-in-this-context-in-Application_5F00_Start.aspx
As solution shortly ,in global.asax I must forward the application_start event to Application_BeginRequest event.
void Application_Start(object sender, EventArgs e) { // sender has type 'System.Web.HttpApplicationFactory' }
Application_BeginRequest(Object source, EventArgs e) | {
// sender has type 'System.Web.HttpApplication' }
Or another solution is, Application_Start event can start later then Application_BeginRequest .
any suggestions ?
I have no option like choosing "classic mode "
Move the code to Application_BeginRequest or Session_Start. You shouldn't use the Request object in Application_Start anyway.
The Request object contains information that is specific for one page request. It doesn't really make any sense to do anything with this information in the Application_Start event.
So, change you app pool mode to classic.

common error page in ASP.NET

How to setup a common error page in ASP.NET website?
Also how to handel the error in Data Access Layer by common error page?
In my current project I'm sticking with Application_Error in the global.asax for showing the end-users a uniform error page in case of any unhandled errors. I added a sendmail call to mail certain exceptions to a mail address to get a better insight in what went wrong (you can't rely on customers/visitors to properly describe the problem).
After sending the mail and/or logging the problem I redirect users to a error.html with a generic errormessage.
In my DAL I try/catch most of the critical functions and show a warning/error accordingly (I return a status/message to show if for example a connection couldn't be made/timed out).
This is the pattern I tend to start with when starting a new app. Apologies this is in VB.NET ;)
In the global.asax Server.Transfer to your custom Error page.
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Server.Transfer("~/Error.aspx", False)
End Sub
Then in your custom error page.
Private Sub Page_Load
Response.Clear()
Dim err As Exception = Server.GetLastError
...
End Sub
Now you can test the Type of the exception. You'll need to recurse down through the inner exceptions as the parent exception will be probably be a general web exception. Get your DAL to throw a custom typed exception and you can test for that and handle differently.
here i am explaining the way to implement a custom error page feature.
Step by step implementation
Creating Error Page : Develop an error page (the page that has to be displayed when error occurs) in the root directory. Lets think that the name of the error page is ErrorPage.aspx
Configuring Web.Config : write the following code in Web.Config
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="~\ErrorPage.aspx"/>
</system.web>
</configuration>
Thats it!!! Now if any error occurs it will redirect to the error page. Now Sometimes we need to display the error. In that case we can write few lines of code in Global.asax
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError().GetBaseException();
Session["LastException"] = ex.ToString();
}
As the exception has been captured and stored in the Session now we can show the message from the session. So we can write the following lines in ErrorPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
lblDisplayError.Text = Session["LastException"].ToString();
}
And we will be able to see the error on the label of ErrorPage.
Hope it will work fine.
Thanks
Pritom Nandy

Resources