Reputation:
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
Upvotes: 3
Views: 2464
Reputation: 18127
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
.
Upvotes: 2
Reputation: 1229
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
Upvotes: 2