在 ASP.NET 应用程序中,典型的错误处理代码涉及 some variation of GetLastError()
,但是还有 HttpContext.AllErrors
其中的收藏GetLastError()
方法只检索第一个。 AllErrors
的场景有哪些?集合可能包含 1 个以上的异常?我想不出任何东西,但显然它是有目的的......
最佳答案
ASP.NET Framework 支持一种不同的模型,在这种模型中,一个请求可能会遇到多个错误,所有这些错误都可以在不停止请求处理的情况下进行报告,从而允许向用户呈现更细致、更有用的信息。
namespace ErrorHandling
{
// sample class adding errors to HttpContext
public partial class SumControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
int? first = GetIntValue("first");
int? second = GetIntValue("second");
if (first.HasValue && second.HasValue)
{
//result.InnerText = (first.Value + second.Value).ToString();
//resultPlaceholder.Visible = true;
}
else
{
Context.AddError(new Exception("Cannot perform calculation"));
}
}
}
private int? GetIntValue(string name)
{
int value;
if (Request[name] == null)
{
Context.AddError(new ArgumentNullException(name));
return null;
}
else if (!int.TryParse(Request[name], out value))
{
Context.AddError(new ArgumentOutOfRangeException(name));
return null;
}
return value;
}
}
}
// intercepting the errors
public class Global : System.Web.HttpApplication
{
protected void Application_EndRequest(object sender, EventArgs e)
{
if (Context.AllErrors != null && Context.AllErrors.Length > 1)
{
Response.ClearHeaders();
Response.ClearContent();
Response.StatusCode = 200;
Server.Execute("/MultipleErrors.aspx");
Context.ClearError();
}
}
}
// MultipleErrors code behind
public partial class MultipleErrors : System.Web.UI.Page
{
public IEnumerable<string> GetErrorMessages()
{
return Context.AllErrors.Select(e => e.Message);
}
}
答案是大量引用来自 appress 的 pro asp.net 4.5
关于asp.net - HttpContext.AllErrors 何时包含多个异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27524447/