Custom Error using Global.asax asp.net - c#

I made an error; the page directs users in case of error in any applications within the website. I made Global.asax rather than using Webconfig. My question is : Is it possible to redirect user from Global.asax for those statusCodes "401", "404" and "500" in case of error rather than using Webconfig ?
In other words, using Global.aspx rather than Webconfig !? I am just curious to know.
Thank you

protected void Application_Error(Object sender, EventArgs e)
{
Exception ex = this.Server.GetLastError();
if(ex is HttpException)
{
HttpException httpEx = (HttpException)ex;
if(httpEx.GetHttpCode() == 401)
{
Response.Redirect("YourPage.aspx");
}
}
}
Yes it is possible. Here is little code example. This should be added in Global.asax.cs.

Never set customErrors to Off in your Web.config file if you do not have an Application_Error handler in your Global.asax file. Potentially compromising information about your Web site can be exposed to anyone who can cause an error to occur on your site.
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
// Get the exception object.
Exception exc = Server.GetLastError();
// Handle HTTP errors
if (exc.GetType() == typeof(HttpException))
{
// The Complete Error Handling Example generates
// some errors using URLs with "NoCatch" in them;
// ignore these here to simulate what would happen
// if a global.asax handler were not implemented.
if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
return;
//Redirect HTTP errors to HttpError page
Server.Transfer("HttpErrorPage.aspx");
}
// For other kinds of errors give the user some information
// but stay on the default page
Response.Write("<h2>Global Page Error</h2>\n");
Response.Write(
"<p>" + exc.Message + "</p>\n");
Response.Write("Return to the <a href='Default.aspx'>" +
"Default Page</a>\n");
// Log the exception and notify system operators
ExceptionUtility.LogException(exc, "DefaultPage");
ExceptionUtility.NotifySystemOps(exc);
// Clear the error from the server
Server.ClearError();
}
Also once can get error code like
exc.GetHttpCode() == 403 so that
if (exc!= null && httpEx.GetHttpCode() == 403)
{
Response.Redirect("/youraccount/error/forbidden", true);
}
else if (exc!= null && httpEx.GetHttpCode() == 404)
{
Response.Redirect("/youraccount/error/notfound", true);
}
else
{
Response.Redirect("/youraccount/error/application", true);
}
Also see Custom error in global.asax

Related

ASP.NET: Only catch certain errors at page level?

Looking at:
https://learn.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/aspnet-error-handling
and specifically:
private void Page_Error(object sender, EventArgs e)
{
Exception exc = Server.GetLastError();
// Handle specific exception.
if (exc is HttpUnhandledException)
{
ErrorMsgTextBox.Text = "An error occurred on this page. Please verify your " +
"information to resolve the issue."
}
// Clear the error from the server.
Server.ClearError();
}
Is there a way to only handle asp.net file uploader file size too big (e.g. over 50MB) and let all other errors be handled at the application level?
BTW, here is code to catch files that are too big at the application level:
//Global.asax
private void Application_Error(object sender, EventArgs e)
{
var ex = Server.GetLastError();
var httpException = ex as HttpException ?? ex.InnerException as HttpException;
if(httpException == null) return;
if (((System.Web.HttpException)httpException.InnerException).WebEventCode == System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge)
{
//handle the error
Response.Write("Too big a file, dude"); //for example
}
}
So in other words, can we "throw" an application level error from a page level error method (e.g., when it's anything other than that file size exception that we want to handle on that specific page)?

Application_Error

I recently discovered that the IIS worker process in production was crashing 2-3 times per week. I noticed in the exception logs that the its because of an UnhandledException. I investigated and found that the Global.asax had no Server.Transfer call.
I then did some googling and it appears that it's better to use Response.Redirect. Is this true, I keep on getting mixed comments on this...
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
if (null != Context && null != Context.AllErrors)
System.Diagnostics.Debug.WriteLine(Context.AllErrors.Length);
//bool isUnexpectedException = true;
HttpContext context = ((HttpApplication)sender).Context;
Exception ex = context.Server.GetLastError();
if (ex.InnerException != null)
ex = ex.InnerException;
LogManager.ExceptionHandler(ex);
Server.Transfer("GeneralError.aspx");
}
It depends on if you would want your user to see the "redirection". Personally I would use Response.Redirect for this case.
Check out this answer on the difference between the two:
https://stackoverflow.com/a/224577/1260077

HttpNotFoundResult causes an HttpException to be thrown?

For testing purposes, I have this method:
public ActionResult Index()
{
System.Diagnostics.Debug.Write("Index");
return new HttpNotFoundResult();
}
The method is being called ('Index' is outputted). Somehow, it is causing a HttpException to be thrown. In my Global.asax file I have an Application_Error implementation:
void Application_Error(object sender, EventArgs e)
{
Exception exc = Server.GetLastError();
if (exc is System.Web.HttpException)
{
string msg = "UrlReferrer: "
+ Context.Request.UrlReferrer + " UserAgent: " + Context.Request.UserAgent
+ " UserHostAddress: " + Context.Request.UserHostAddress + " UserHostName: "
+ Context.Request.UserHostName;
ErrorHandler.Error(exc.Message, msg);
}
else {
...
}
}
This method is being called after the system has processed the request for Index. I think that the HttpNotFoundResult causes the exception to be thrown - or perhaps the exception is thrown for any ActionResult with a status code of 404.
This is quite annoying, as it is side-stepping the OnException handler on my controller. For my website, Application_Error is supposed to be a last-ditch fallback - most normal errors are intended to be handled in other places (by the controllers, or action filters). I only want Application_Error to log completely unexpected exceptions, or 404s for things like image or .js files.
Is there a way to stop asp.net from throwing exceptions for programatically generated 404s? Alternatively, is there a way to determine in Application_Error if the HttpException was caused by a programatically generated 404?
You can create a custom exception filter that handles 404 exceptions raised by all the actions. You could use HttpContext.Items collection to track whether it is a programatically raised 404 or not.
Custom exception filter
public class NotFoundExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// ignore if the exception is already handled or not a 404
if (filterContext.ExceptionHandled || new HttpException(null, filterContext.Exception).GetHttpCode() != 404)
return;
filterContext.HttpContext.Items.Add("Programmatic404", true);
filterContext.ExceptionHandled = true;
}
}
You need to apply NotFoundExceptionFilter as a global filter.
Application_Error event
public static void Application_Error(object sender, EventArgs e)
{
var httpContext = ((MvcApplication)sender).Context;
// ignore if it is a programatically raised 404
if(httpContext.Items["Programmatic404"] != null && bool.Parse(httpContext.Items["Programmatic404"].ToString()))
return;
// else, Log the exception
}

How to change where UnauthorizedAccessException redirects to in ASP.Net

Pretty straightforward.
I'm throwing an UnauthorizedAccessException in an AuthorizationFilter. I want UnauthorizedAccessException to head to an Error page, NOT to the /Account/Login page.
How can I make that change?
Try setting up something like this in global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
// excpt is the exception thrown
// The exception that really happened is retrieved through the GetBaseException() method
// because the exception returned by the GetLastError() is a HttpException
Exception excpt = Server.GetLastError().GetBaseException();
if(excpt is UnauthorizedAccessException)
{
// redirect here
}
}
You can use multiple exception handlers
try
{
// code here
}
catch (UnauthorizedAccessException)
{
Response.Redirect(errorPageUrl, false);
}
catch (Exception)
{
Response.Redirect(loginPageUrl, false);
}

Trying to convert Global.asax 1.0 file to 3.5 Issues with Application_Error + Session and Redirect

So in the Global.asax is this:
protected void Application_Error(object sender, System.EventArgs
{
Session["CustomError"] = Server.GetLastError();
Server.ClearError();
Response.Redirect("~/ErrorPage.aspx");
}
And in ErrorPage.aspx is this:
private void Page_Load(object sender, System.EventArgs e)
{
Exception currentException = ((Exception)Session["CustomError"]).InnerException;
// Writes the error message
if (currentException != null)
txtErrorMessage.Text = currentException.Message;
// Loops through the inner exceptions.
currentException = (Exception)Session["CustomError"];
while (currentException != null)
{
message.Append(currentException.Message).Append("\r\n").Append(currentException.StackTrace);
message.Append("\n==============================================\n");
currentException = currentException.InnerException;
}
As this is old 1.0 code it barfs when converted to a 3.5 Global.asax file. It tells me that "Session" is not available and also that I can't redirect?? I think one of the issues may be that there is also an error being thrown from Application_Start. But if I comment out all the application start code I still get errors but they never get redirected to the error page.
This link might help: Exceptional Gotchas!.
In addition, use the web.config file to define your default redirect page for errors.

Categories

Resources