custom error page in asp.net

吃可爱长大的小学妹 提交于 2019-12-11 11:44:25

问题


I have web application in asp.net. 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.

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

回答1:


You can handle it in 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;
}



回答2:


Please do not use Redirection as a means of displaying error messages, because it breaks 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. 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.

I recommend using IIS Manager to generate your web.config file for you. As for handling the error, open your Global.asax.cs file and add a method for Application_Error, then call Server.GetLastError() from within.




回答3:


In the 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

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



回答4:


Use Elmah dll for displaying your error with nice UI. You can maintain log using this DLL.




回答5:


You can access the error using Server.GetLastError;

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

For more information : HttpServerUtility.GetLastError Method



来源:https://stackoverflow.com/questions/13837085/custom-error-page-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!