17.错误页

  • 当页面发生错误的时候,ASP.net会将错误信息展示出来,这样一来不好看,二来会泄露网站的内部实现信息,给网站带来安全隐患。因此需要定制错误页,发生错误时显示开发人员定制的页面。
  • 配置web.config,配置customErrors区域
    • <customErrors mode="RemoteOnly" defaultRedirect="MyErrorPage.aspx">
    •    <error statusCode="403" redirect="NoAccess.htm"/>
    •    <error statusCode="404" redirect="FileNotFound.htm" />
    • <customErrors>
  • mode三个可选值:on:总是显示定制错误页面;off:不显示定制错误页面,直接显示调用堆栈等异常信息;remoteonle:对于本机访问显示调用堆栈等异常信息,对于外部用户的显示定制错误页面。一般设置为remoteonly,这样发生错误的话,管理员可以在服务器的浏览器中看详细错误信息,普通用户看不到。可以在定义错误页中判断Request.UserHostAddress来设置某些ip看到异常信息,可以读取Session,如果是管理员则可以看到异常信息。
  • error子元素设定对于不同的状态码使用不同的错误页,很多网站把404做成一个特殊的错误页。没有单独设置的状态码错误则显示defaultRedirect中指定的页面。
  • 错误页即可以使用htm页面,也可以使用aspx页面。在aspx页面中可以用HttpContext.Current.Server.GetLastError()拿到异常对象,一般不要把异常信息显示给用户,而是使用异常日志,把异常记录起来,如果要在错误页中拿到异常对象,就要在customErrors中设置redirectMode="ResponseRewrite",因为默认是客户端重定向的,在错误页中就拿不到异常对象了。

示例:

   1.建立两个页面,一个为访问特定文件时找不到文件的出错页FileNotFound.htm,另一个为其它出错时的错误页:defaultErr.aspx。

   2.建立ErrorTest.aspx,当运行此页时,系统会出错

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ErrorTest.aspx.cs" Inherits="企业网站.ErrorTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

在它的page_load事件中的代码:

            if (!IsPostBack)
            {
                SqlConnection conn = new SqlConnection("IP:127.0.0.1&db=tt");
                conn.Open();
            }

3.设置web.config文件

<?xml version="1.0" encoding="utf-8"?>

<!--
  有关如何配置 ASP.NET 应用程序的详细消息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>   
  
    <system.web>
      <customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/ErrorPages/defaultErr.aspx">
        <error statusCode="404" redirect="~/ErrorPages/FileNotFound.htm" />
      </customErrors>
        <compilation debug="true" targetFramework="4.0" />
      <httpRuntime requestValidationMode="2.0"/>
    </system.web>

</configuration>

4.当产生错误时,有个日记用来记录错误的具体信息,在项目中建立ErrorRecords.txt文件

在defaultErr.aspx页的Page_Load事件中写入以下代码:

 if (!IsPostBack)
            {
              Exception ex=  HttpContext.Current.Server.GetLastError();
              File.AppendAllText(Server.MapPath("~/ErrorRecords.txt"), ex.StackTrace);
            }

5.运行ErrorTest.aspx,会自动呈现defaultErr.aspx页面,并会把出错的具体信息写到ErrorRecords.txt中。

 

posted on 2013-07-06 10:47  天上星  阅读(299)  评论(0编辑  收藏  举报

导航