欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# web.config之节点说明案例详解

程序员文章站 2022-06-15 18:38:36
节点用于定义一些自定义错误信息的信息。此节点有mode和defaultredirect两个属性,其中defaultredirect属性是一个可选属性,表示应用程...
<customerrors>节点用于定义一些自定义错误信息的信息。此节点有mode和defaultredirect两个属性,其中defaultredirect属性是一个可选属性,表示应用程序发生错误时重定向到的默认url,如果没有指定该属性则显示一般性错误。mode属性是一个必选属性,它有三个可能值,它们所代表的意义分别如下:
mode 说明
on 表示在本地和远程用户都会看到自定义错误信息。
off 禁用自定义错误信息,本地和远程用户都会看到详细的错误信息。
remoteonly 表示本地用户将看到详细错误信息,而远程用户将会看到自定义错误信息。
这里有必要说明一下本地用户和远程用户的概念。当我们访问asp.net应用程时所使用的机器和发布asp.net应用程序所使用的机器为同一台机器时成为本地用户,反之则称之为远程用户。在开发调试阶段为了便于查找错误mode属性建议设置为off,而在部署阶段应将mode属性设置为on或者remoteonly,以避免这些详细的错误信息暴露了程序代码细节从而引来黑客的入侵。
下面我们添加一个页面customerrorsdemo.aspx,在它的page_load事件里抛出一个异常,代码如下:
using system;
using system.data;
using system.configuration;
using system.collections;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;

public partial class customerrorsdemo : system.web.ui.page
{
    protected void page_load(object sender, eventargs e)
    {
        throw new exception("故意抛出的异常。");
    }
}
我们先配置<customerrors>如下:
<customerrors mode="remoteonly"> 
     <error statuscode="403" redirect="noaccess.htm" /> 
     <error statuscode="404" redirect="filenotfound.htm" /> 
</customerrors>
这时本地运行customerrorsdemo.aspx的效果如下:
远程访问时看到的效果:
如果我们将customerrors的mode属性设置为“on”本地运行和远程访问都会看到如下效果:
如果将customerrors的mode属性设置为“off”本地运行和远程访问都会看到如下效果:
<error>子节点
在<customerrors>节点下还包含有<error>子节点,这个节点主要是根据服务器的http错误状态代码而重定向到我们自定义的错误页面,注意要使<error>子节点下的配置生效,必须将<customerrors>节点节点的mode属性设置为“on”。下面是一个例子:
<customerrors mode="on" defaultredirect="genericerrorpage.htm"> 
     <error statuscode="403" redirect="403.htm" /> 
     <error statuscode="404" redirect="404.htm" /> 
</customerrors>
在上面的配置中如果用户访问的页面不存在就会跳转到404.htm页面,如果用户没有权限访问请求的页面则会跳转到403.htm页面,403.htm和404.htm页面都是我们自己添加的页面,我们可以在页面中给出友好的错误提示。

到此这篇关于c# web.config之<customerrors>节点说明案例详解的文章就介绍到这了,更多相关c# web.config之<customerrors>节点说明内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: C# customErrors