发布:2021/11/26 16:54:46作者:管理员 来源:本站 浏览次数:901
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace xland
{
public class AspExceptionHandler : IHttpModule, IHttpHandler
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.Error += new EventHandler(ErrorHandler);
}
private void ErrorHandler(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
try
{
// Gather information
Exception currentException = application.Server.GetLastError(); ;
String errorPage = "http://www.begon.cn/error.aspx";
HttpException httpException = currentException as HttpException;
if (httpException == null || httpException.GetHttpCode() != 404)
{
application.Server.Transfer(errorPage, true);
}
//The error is a 404
else
{
// Continue
application.Server.ClearError();
//Try and redirect to the proper page.
String requestedFile = application.Request.Url.AbsolutePath.Trim('/').Split('/').Last();
// Redirect if required
string redirectURL = requestedFile.Trim('/');
if (!string.IsNullOrEmpty(redirectURL))
{
//Redirect to the proper URL
}
//If we can't redirect properly, we set the statusCode to 404.
else
{
//Report the 404
}
}
}
catch (Exception ex)
{
}
}
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
if (!File.Exists(context.Request.PhysicalPath))
{
throw new HttpException(404, String.Format("The file {0} does not exist", context.Request.PhysicalPath));
}
else
{
context.Response.TransmitFile(context.Request.PhysicalPath);
}
}
}
}
在ProcessRequest方法(IHttpHandler所需)中,我检查文件是否存在.
如果它不存在,我抛出一个由我的类的HttpModule部分捕获的HttpException.