网站中目前web.config配置如下
<customErrors mode="On" redirectMode="ResponseRedirect"> <error statusCode="500" redirect="~/Error.aspx?id=500" /> <error statusCode="404" redirect="~/Error.aspx?id=404" /> </customErrors>
当redirectMode="ResponseRewrite"时Error.aspx中
var ex = Server.GetLastError(); //返回异常对象
当redirectMode="ResponseRedirect"时Error.aspx中
var ex = Server.GetLastError(); //返回null
问题是:我需要使用redirectMode="ResponseRedirect"并且在Error.aspx中能够获取错误异常。请问这个是什么原因?
HttpContext context = HttpContext.Current;
Exception exception = context.Server.GetLastError();
全局错误:
void Application_Error(object sender, EventArgs e) { //This block will execute when there any error on the page and we can fetch the current context HttpContext context = HttpContext.Current; //This block will fetch current excpetion Exception exception = context.Server.GetLastError(); //This block is used for creating custom error message StringBuilder errorDetails = new StringBuilder(); errorDetails.Append("<br>Incorrect URL: "); errorDetails.Append(context.Request.Url.AbsoluteUri); errorDetails.Append("<br>Source: "); errorDetails.Append(exception.Source); errorDetails.Append("<br>Message: "); errorDetails.Append(exception.Message); errorDetails.Append("<br>Stack trace: "); errorDetails.Append(exception.StackTrace); //This block is used for fetching the error code HttpException httpException = (HttpException)exception; int errorCode = httpException.GetHttpCode(); //This block will write the custom error message on the page context.Response.Write(errorDetails.ToString()); //This will clear the error from the server and let the page finish context.Server.ClearError(); }
指定页面错误:
protected override void OnError(EventArgs e) { //This block will execute when there any error on the page and we can fetch the current context HttpContext context = HttpContext.Current; //This block will fetch current excpetion Exception exception = context.Server.GetLastError(); //This block is used for creating custom error message StringBuilder errorDetails = new StringBuilder(); errorDetails.Append("<br>Incorrect URL: "); errorDetails.Append(context.Request.Url.AbsoluteUri); errorDetails.Append("<br>Source: "); errorDetails.Append(exception.Source); errorDetails.Append("<br>Message: "); errorDetails.Append(exception.Message); errorDetails.Append("<br>Stack trace: "); errorDetails.Append(exception.StackTrace); //This block is used for fetching the error code HttpException httpException = (HttpException)exception; int errorCode = httpException.GetHttpCode(); //This block will write the custom error message on the page context.Response.Write(errorDetails.ToString()); //This will clear the error from the server and let the page finish context.Server.ClearError(); base.OnError(e); }
Global.asax里Application_Error能够拿到Server.GetLastError。我问的问题是在自定义的页面里怎么取出那个异常对象。
@dotNetDR_: 上面不是有吗,重写OnError方法。