当发生错误并在页面中拒绝访问时,重定向到错误页面
本文关键字:错误 重定向 拒绝访问 | 更新日期: 2023-09-27 18:17:26
嗨,我正在做我的项目在asp.net现在我有一个按设计的页面错误现在如何可以重定向到错误页面自动当错误发生在页面加载查找该页的错误代码
错误如404 403 400 500错误代码
您可以使用Global.asax
并在其中使用Application_Error方法处理异常并重定向。下面是我正在做的:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Context.Error;
if (ex is HttpUnhandledException)
{
ex = Context.Error.InnerException;
}
if (ex.GetType().Name == "FileNotFoundException")
{
//ignore
}
else
{
try
{
if ((ex as HttpException).GetHttpCode() == 404)
{
// Page Not found, redirect
if (!ex.Message.Contains("error.aspx"))
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", "~/error.aspx");
Response.End();
}
}
}
catch (Exception ThrownException)
{
//log
}
}
}
添加全局。一个带有以下代码的页面
protected void Application_Error(Object sender, EventArgs e)
{
HttpException ex = (HttpException)Server.GetLastError();
int httpCode = ex.GetHttpCode();
if (httpCode == 404)
{
//do 404 code work here
}
if (httpCode == ???)
{
//do ??? code work here
}
}