ASP.NET 在global中拦截404错误的实现方法

ASP.NET应用程序中,可以在全局应用程序类(Global.asax)的Application_Error事件中拦截404错误。实现方法如下:

1. 打开全局应用程序类文件Global.asax,添加Application_Error事件处理方法:

void Application_Error(object sender, EventArgs e) 
{
    // 代码逻辑
}

2. 在Application_Error方法中获取对HttpContext对象的引用,通过它获取对Server对象的引用:

HttpContext context = HttpContext.Current;
Server server = context.Server;

3. 通过Server对象的GetLastError方法获取最后一个发生的HTTP错误:

 
HttpException lastError = server.GetLastError() as HttpException;

4. 检查lastError对象的ErrorCode属性是否为404,如果是则表示发生了404错误:

if (lastError != null && lastError.ErrorCode == 404)
{
    // 处理404错误逻辑
}

5. 处理404错误,可以重定向到自定义错误页面或任何逻辑:

context.Response.Redirect("~/404.htm");  // 重定向到404.htm页面
// 或任何其他逻辑

6. 阻止异常被传播,防止触发ASP.NET的默认错误页面:

server.ClearError(); 

完整的Global.asax.cs代码如下:

void Application_Error(object sender, EventArgs e) 
{
    HttpContext context = HttpContext.Current;
    Server server = context.Server;
    HttpException lastError = server.GetLastError() as HttpException;

    if (lastError != null && lastError.ErrorCode == 404)
    {
        context.Response.Redirect("~/404.htm");
        server.ClearError();
    }
} 

每当发生404错误,该方法将重定向到404.htm页面并清除错误,阻止显示默认错误页面。

通过在Global.asax的Application_Error事件中添加处理逻辑,可以有效拦截ASP.NET应用程序产生的404错误,实现自定义错误处理页面或其他操作。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
评论 抢沙发

请登录后发表评论