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

标签 asp.net error-handling httpcontext

在 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/

相关文章:

asp.net - 更改 Razor View 似乎会重新启动我的应用程序

bash - 当Bash出现表达式错误时如何退出,例如[: -ne: unary operator expected

.net - 缺少 HttpContext

c# - SQL Server 对象资源管理器不显示我的数据库

c# - 维护 html 元素的 View 状态?

asp.net - Crystal 报表错误 : Could not load file or assembly While loading in asp. 网络配置文件

math - 为什么这个哥德巴赫猜想程序在Prolog中不起作用?

python - 为什么我pyqt5告诉我,如果我知道这个小部件不存在?

asp.net - HttpContext.Current.User.Identity.Name 的问题

asp.net - 在什么情况下 HttpContext.Current.Session 可以为 null?