簡體   English   中英

使用Global.asax asp.net的自定義錯誤

[英]Custom Error using Global.asax asp.net

我犯了一個錯誤; 如果網站內的任何應用程序出現錯誤,頁面會指導用戶。 我創建了Global.asax而不是使用Webconfig。 我的問題是:如果出現錯誤而不是使用Webconfig,是否可以將用戶從Global.asax重定向到那些statusCodes“401”,“404”和“500”?

換句話說,使用Global.aspx而不是Webconfig! 我很想知道。

謝謝

如果您的Global.asax文件中沒有Application_Error處理程序,請勿在Web.config文件中將customErrors設置為Off 任何可能導致您網站上出現錯誤的人都可能會泄露有關您網站的潛在危害信息。

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

    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添加。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM