ASP.NET 2.0: Best Practice for Writing an Error Page

The asp.net 2.0 website is the best way to write an error page. I saw the following section in the following location:

Web.config
<customErrors mode="RemoteOnly" defaultRedirect="~/Pages/Common/DefaultRedirectErrorPage.aspx">

Global.asax
void Application_Error(object sender, EventArgs e) 
{ 
}

I do not understand how to use both of them in the best way for error handling.

Please help me get the best fit.

+5
source share
2 answers

In my global asax, I always check what type of http error it is ...

then go to the page with the correct error specified in web.config I like to process ordinary suspects, 404 (lost page) and 500 (server error)

http importaint, , :

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

my web.config .

<customErrors mode="On"  defaultRedirect="~/error.aspx"  >
  <error statusCode="404" redirect="~/lost.aspx"  />
  <error statusCode="500" redirect="~/error.aspx"  />
</customErrors>

, , , , , .

, ,

-.

, , 401/403?

protected void Application_Error(object sender, EventArgs e)
{
    var context = Context;


    var error = context.Server.GetLastError() as HttpException;
    var statusCode = error.GetHttpCode().ToString();

    // we can still use the web.config custom errors information to
    // decide whether to redirect
    var config = (CustomErrorsSection)WebConfigurationManager.GetSection("system.web/customErrors");
    if (config.Mode == CustomErrorsMode.On ||
        (config.Mode == CustomErrorsMode.RemoteOnly && context.Request.Url.Host != "localhost"))
    {
        // set the response status code
        context.Response.StatusCode = error.GetHttpCode();

        // Server.Transfer to correct ASPX file for error
        if (config.Errors[statusCode] != null)
        {

            HttpContext.Current.Server.Transfer(config.Errors[statusCode].Redirect);
        }
        else
            HttpContext.Current.Server.Transfer(config.DefaultRedirect);
    }
}

, i, , -... , http- 302, , ... 200 (ok).

302 → 200, 302 → 404 , 404...

404 , http:

protected void Page_PreRender(object sender, EventArgs e)
{
    Response.Status = "404 Lost";
    Response.StatusCode = 404;

}

, , , , web.config... http://helephant.com/2009/02/improving-the-way-aspnet-handles-404-requests/

, 404 404 . , , , .

404. Soft 404 arent , , 404, 404 - , - , . , , , .

, 404 , , , 404 , . 404 Google -:

server.clearerror() global.asax?

  • , , ? , ?

web.config error.aspx 500, - defaultredirect

  • 2, / , . , ... , . . 403, 401, 400 ( , )

error.aspx lost.aspx.

  • - . , , , . , . log , , ... .
+9

BigBlondeViking , , , 403 ( ASP /Scripts/or/Content/directories.) , , Application_Error. ( " " - !)

protected void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
    if (!Context.Items.Contains("HasHandledAnError")) // have we alread processed?
    {
        if (Response.StatusCode > 400 &&  // any error
            Response.StatusCode != 401)   // raised when login is required
        {
            Exception exception = Server.GetLastError();    // this is null if an ASP error
            if (exception == null)
            {
                exception = new HttpException((int)Response.StatusCode, HttpWorkerRequest.GetStatusDescription(Response.StatusCode));
            }
            HandleRequestError(exception); // code shared with Application_Error
        }
    }
}

. ASP.NET MVC, , . , / ;

public ActionResult ServerError(Exception exception)
{
    HttpException httpException = exception as HttpException;
    if(httpException != null)
    {
        switch (httpException.GetHttpCode())
        {
            case 403:
            case 404:
                Response.StatusCode = 404;
                break;
        }
        // no email...
        return View("HttpError", httpException);
    }
    SendExceptionMail(exception);
    Response.StatusCode = 500;
    return View("ServerError", exception);
}

OBJECT ( ), :

protected void HandleRequestError(Exception exception)
{
    if (Context.Items.Contains("HasHandledAnError"))
    {
        // already processed
        return;
    }
    // mark as processed.
    this.Context.Items.Add("HasHandledAnError", true);

    CustomErrorsSection customErrorsSection = WebConfigurationManager.GetWebApplicationSection("system.web/customErrors") as CustomErrorsSection;

    // Do not show the custom errors if
    // a) CustomErrors mode == "off" or not set.
    // b) Mode == RemoteOnly and we are on our local development machine.
    if (customErrorsSection == null || !Context.IsCustomErrorEnabled ||
        (customErrorsSection.Mode == CustomErrorsMode.RemoteOnly && Request.IsLocal))
    {
        return;
    }

    int httpStatusCode = 500;   // by default.
    HttpException httpException = exception as HttpException;
    if (httpException != null)
    {
        httpStatusCode = httpException.GetHttpCode();
    }

    string viewPath = customErrorsSection.DefaultRedirect;
    if (customErrorsSection.Errors != null)
    {
        CustomError customError = customErrorsSection.Errors[((int)httpStatusCode).ToString()];
        if (customError != null && string.IsNullOrEmpty(customError.Redirect))
        {
            viewPath = customError.Redirect;
        }
    }

    if (string.IsNullOrEmpty(viewPath))
    {
        return;
    }

    Response.Clear();
    Server.ClearError();

    var httpContextMock = new HttpContextWrapper(Context);
    httpContextMock.RewritePath(viewPath);
    RouteData routeData = RouteTable.Routes.GetRouteData(httpContextMock);
    if (routeData == null)
    {
        throw new InvalidOperationException(String.Format("Did not find custom view with the name '{0}'", viewPath));
    }
    string controllerName = routeData.Values["controller"] as string;
    if (String.IsNullOrEmpty(controllerName))
    {
        throw new InvalidOperationException(String.Format("No Controller was found for route '{0}'", viewPath));
    }
    routeData.Values["exception"] = exception;

    Response.TrySkipIisCustomErrors = true;
    RequestContext requestContext = new RequestContext(httpContextMock, routeData);
    IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
    IController errorsController = factory.CreateController(requestContext, controllerName);
    errorsController.Execute(requestContext);
}
+3

All Articles