C# 使用Global.asax asp.net时出现自定义错误

C# 使用Global.asax asp.net时出现自定义错误,c#,asp.net,C#,Asp.net,我犯了一个错误;如果网站内的任何应用程序出现错误,该页面将指导用户。我制作了Global.asax,而不是使用Webconfig。我的问题是:如果出现错误,是否可以将用户从Global.asax重定向到那些状态码“401”、“404”和“500”,而不是使用Webconfig 换句话说,使用Global.aspx而不是Webconfig!?我只是想知道 谢谢如果Global.asax文件中没有Application\u Error处理程序,请不要在Web.config文件中将customErro

我犯了一个错误;如果网站内的任何应用程序出现错误,该页面将指导用户。我制作了
Global.asax
,而不是使用Webconfig。我的问题是:如果出现错误,是否可以将用户从
Global.asax
重定向到那些状态码“401”、“404”和“500”,而不是使用Webconfig

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


谢谢

如果
Global.asax
文件中没有
Application\u 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();
}
也看到


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

这是可能的,但我真的看不到任何附加值…使用web.config更好,只需在谷歌上搜索in-web.config检查我的答案,并告诉我是否有帮助!您需要清除服务器上的错误吗?GetHttpCode给了我一个错误?不,你不需要清除任何东西。GetHttpCode为您提供了错误代码,可以是401404403等等。感谢您的回复,但注意到if(httpEx.GetHttpCode()==401)中的一个代码中存在打字错误
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);
    }
    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");
              }
         }
    }