使用Global.asax asp.net的自定义错误

时间:2014-12-29 12:19:39

标签: c# asp.net

我犯了错误;如果网站内的任何应用程序出现错误,页面会指导用户。我做了Global.asax而不是使用Webconfig。我的问题是:是否可以将用户从Global.asax重定向到那些statusCodes" 401"," 404"和" 500"如果是错误而不是使用Webconfig?

换句话说,使用Global.aspx而不是Webconfig!我很想知道。

谢谢

2 个答案:

答案 0 :(得分:2)

如果您的customErrors文件中没有Off处理程序,请勿在您的Web.config文件中将Application_Error设置为Global.asax。任何可能导致您网站上出现错误的人都可能会泄露有关您网站的潜在信息。

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();
}

也可以获得像

这样的错误代码
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);
    }

另见Custom error in global.asax

答案 1 :(得分:2)

    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");
              }
         }
    }

是的,这是可能的。这是一个小代码示例。这应该在Global.asax.cs中添加。