简体   繁体   English

asp.net中的自定义错误页面

[英]custom error page in asp.net

I have web application in asp.net. 我在asp.net中有Web应用程序。 I have to implement custom error page. 我必须实现自定义错误页面。 Means if any eror occurs(runtime). 表示是否发生错误(运行时)。 I have to display exception and stacktrace on errorpage.aspx shall i handle from master page or on page level and how. 我必须在errorpage.aspx上显示异常和stacktrace,我应该从母版页还是在页面级别上以及如何处理。

<customErrors mode="On" defaultRedirect="~/Error_Page.aspx"></customErrors>

You can handle it in global.asax : 您可以在global.asax中处理它:

protected void Application_Error(object sender, EventArgs e)
{
   Exception ex = System.Web.HttpContext.Current.Error;
   //Use here
   System.Web.HttpContext.Current.ClearError();
   //Write custom error page in response
   System.Web.HttpContext.Current.Response.Write(customErrorPageContent);
   System.Web.HttpContext.Current.Response.StatusCode = 500;
}

Please do not use Redirection as a means of displaying error messages, because it breaks HTTP. 请不要使用重定向作为显示错误消息的方法,因为它会破坏HTTP。 In case of an error, it makes sense for the server to return an appropriate 4xx or 5xx response, and not a 301 Redirection to a 200 OK response. 如果发生错误,则服务器应该返回适​​当的4xx或5xx响应,而不是返回到200 OK响应的301重定向。 I don't know why Microsoft added this option to ASP.NET's Custom Error Page feature, but fortunately you don't need to use it. 我不知道为什么Microsoft将此选项添加到ASP.NET的“自定义错误页面”功能中,但是幸运的是您不需要使用它。

I recommend using IIS Manager to generate your web.config file for you. 我建议使用IIS管理器为您生成web.config文件。 As for handling the error, open your Global.asax.cs file and add a method for Application_Error , then call Server.GetLastError() from within. 至于处理错误,请打开Global.asax.cs文件并为Application_Error添加方法,然后从内部调用Server.GetLastError()

Use Elmah dll for displaying your error with nice UI. 使用Elmah dll通过漂亮的UI显示错误。 You can maintain log using this DLL. 您可以使用此DLL维护日志。

In the Global.asax 在Global.asax中

void Application_Error(object sender, EventArgs e) 
{    
    Session["error"] = Server.GetLastError().InnerException; 
}
void Session_Start(object sender, EventArgs e) 
{      
    Session["error"] = null;
}

In the Error_Page Page_Load event 在Error_Page Page_Load事件中

if (Session["error"] != null)
{
    // You have the error, do what you want
}

You can access the error using Server.GetLastError; 您可以使用Server.GetLastError访问错误;

var exception = Server.GetLastError();
  if (exception != null)
    {
       //Display Information here
    }

For more information : HttpServerUtility.GetLastError Method 有关更多信息: HttpServerUtility.GetLastError方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM