Hem*_*yal 5 asp.net error-handling global-asax
在asp.net 2.0网站上,编写错误页面的最佳方法是什么.我在以下位置看过以下部分:
<customErrors mode="RemoteOnly" defaultRedirect="~/Pages/Common/DefaultRedirectErrorPage.aspx">
Run Code Online (Sandbox Code Playgroud)
void Application_Error(object sender, EventArgs e)
{
}
Run Code Online (Sandbox Code Playgroud)
我没有得到如何以最佳方式使用它们来进行错误处理.
请指导我最好的方法.
在我的全局asax中,我总是检查它是什么类型的http错误...
然后转移到web.config中指定的正确错误页面我喜欢处理通常的嫌疑人,404(丢失页面)和500(服务器错误)
http状态代码的一些背景是importen,以了解它们的处理原因:
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
我的web.config看起来像这样
<customErrors mode="On" defaultRedirect="~/error.aspx" >
<error statusCode="404" redirect="~/lost.aspx" />
<error statusCode="500" redirect="~/error.aspx" />
</customErrors>
Run Code Online (Sandbox Code Playgroud)
我丢失的页面中有逻辑,试图找到他们可能一直在寻找的页面的链接,以及其他一些格式.
我的错误页面有点不同,显示一些错误消息,
所以我处理两者不同.
取决于您是否有安全的网站区域,您可能需要处理401/403?
protected void Application_Error(object sender, EventArgs e)
{
var context = Context;
var error = context.Server.GetLastError() as HttpException;
var statusCode = error.GetHttpCode().ToString();
// we can still use the web.config custom errors information to
// decide whether to redirect
var config = (CustomErrorsSection)WebConfigurationManager.GetSection("system.web/customErrors");
if (config.Mode == CustomErrorsMode.On ||
(config.Mode == CustomErrorsMode.RemoteOnly && context.Request.Url.Host != "localhost"))
{
// set the response status code
context.Response.StatusCode = error.GetHttpCode();
// Server.Transfer to correct ASPX file for error
if (config.Errors[statusCode] != null)
{
HttpContext.Current.Server.Transfer(config.Errors[statusCode].Redirect);
}
else
HttpContext.Current.Server.Transfer(config.DefaultRedirect);
}
}
Run Code Online (Sandbox Code Playgroud)
我服务器转移的原因是搜索引擎不会混淆,并保持我的网站管理员日志有意义...如果你重定向你返回一个http状态302告诉浏览器转到重定向到...的页面然后这下一页返回状态代码200(ok).
302 - > 200,甚至302 - > 404有不同的含义,只有404 ......
然后说我的404错误页面我确保我设置了http错误的状态代码:
protected void Page_PreRender(object sender, EventArgs e)
{
Response.Status = "404 Lost";
Response.StatusCode = 404;
}
Run Code Online (Sandbox Code Playgroud)
这篇文章对我很有帮助,我知道我想做什么,但我喜欢这段代码看看web.config设置... http://helephant.com/2009/02/improving-the-way-aspnet-手柄-404-请求/
返回正确的状态代码
默认情况下,处理404错误页面的页面不会向浏览器返回404状态代码.它显示您提供给用户的错误消息,但没有任何额外信息将页面标记为错误页面.
这被称为软404.软404页面不如返回404状态代码那样好,因为返回404状态代码可以让任何访问您文件的页面都是错误页面,而不是您站点的真实页面.这对搜索引擎非常有用,因为他们知道他们应该从索引中删除死页,这样用户就不会在结果页面中跟踪到您网站的死链接.
返回404状态代码的页面对于错误检测也很有用,因为它们将记录在您的服务器日志中,因此如果您有意外的404错误,它们将很容易找到.以下是Google网站管理员工具中404错误报告的示例:
EDITS
是否需要在global.asax中编写server.clearerror()?它有什么影响
为什么在web.config中我们应该将error.aspx写入状态代码500两次,另一个是defaultredirect
你能告诉我error.aspx和lost.aspx的代码吗?
| 归档时间: |
|
| 查看次数: |
4297 次 |
| 最近记录: |