HttpContext.AllErrors何时包含多个异常?

时间:2014-12-17 11:21:04

标签: asp.net error-handling httpcontext

在ASP.NET应用程序中,典型的错误处理代码涉及some variation of GetLastError(),但是还有HttpContext.AllErrors集合,其中GetLastError()方法仅检索第一个。{1}}方法。 AllErrors集合可能包含多于1个异常的情况是什么?我无法想到任何事情,但显然它是出于某种目的......

1 个答案:

答案 0 :(得分: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
相关问题