轉載:
asp.net中當伺服器出錯時顯示指定的錯誤頁面同時把錯誤資訊寫入系統日誌文檔
一,在web.config中填寫出錯時顯示的頁面,能夠根據不同的statuscode顯示不同的出錯頁面。
<customerrors mode="on" //假如配置為off則出錯只返回錯誤資訊,不會跳到自己的指定頁面defaultredirect="/error/customerrorpage.aspx">
<error statuscode="404" redirect="/error/404page.aspx"/>
<error statuscode="403" redirect="/error/403page.aspx"/>
</customerrors>
二,在global.asax文檔中添加應用出錯代碼,寫入系統日誌文檔
protected void application_error(object sender, eventargs e)
{
exception lasterror = server.getlasterror();
string errmessage = lasterror.tostring();
string logname = "mylog";
string message = "url " + request.path + " error: " + errmessage;
// create event log if it doesnt exist
if (!eventlog.sourceexists(logname))
{
eventlog.createeventsource(logname, logname);
}
eventlog log = new eventlog();
log.source = logname;
//these are the five options that will display a different icon.
log.writeentry(message, eventlogentrytype.information, 1);
log.writeentry(message, eventlogentrytype.error, 2);
log.writeentry(message, eventlogentrytype.warning, 3);
log.writeentry(message, eventlogentrytype.successaudit, 4);
log.writeentry(message, eventlogentrytype.failureaudit, 5);
}
三,現在您能夠進行測試了。
我在default.aspx.cs中產生一個錯誤,果然跳到預設的錯誤頁面!
private void page_load(object sender, system.eventargs e)
{
// put user code to initialize the page here
try
{
int y=0;
int x=1/y;
}
catch (exception err)
{
throw new exception("404");//我想產生不同的錯誤,對應web.config中的statuscode,該如何??
//err.
}
同理:如果要在所有入口處判斷SESSION是否到期,例如登入資訊,也可以通過 application的全域實踐來進行監控
Application事件的執行順序-.NET教程,Asp.Net研發 |
|
|
執行application_beginrequest 執行application_authenticaterequest 執行application_authorizerequest 執行application_resolverequestcache 執行application_acquirerequeststate 執行application_prerequesthandlerexecute 執行application_postrequesthandlerexecute 執行application_releaserequeststate 執行application_updaterequestcache 執行application_endrequest
|
類似與JAVA中的攔截器Filter,見前期的文章【使用filter攔截器判斷會話是否丟失】 |