【问题标题】:trapping an exception using IExceptionFilter and redirecting permanently binds the path to error page使用 IExceptionFilter 捕获异常并重定向永久绑定到错误页面的路径
【发布时间】:2016-10-19 23:48:39
【问题描述】:

我试图通过首先生成崩溃代码然后将用户重定向到错误页面来将未处理的异常重定向到错误页面。问题是在第一次发生后,原来的 url/action 被永久映射到错误页面 url,甚至不再进入 OnException 方法。即使在我修复了原始异常的原因之后,url/action 仍然被映射为只是重定向到错误页面。不确定这是在哪里发生或如何解决。下面是代码:

public class UnhandledExceptionFilter : IExceptionFilter
{
       protected static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        public void OnException(ExceptionContext filterContext)
        {
            var ex = filterContext.Exception;

            if (ex != null)
            {
                string user = "";
                try
                {
                    user = Managers.UserManager.FindByUsername(filterContext.HttpContext.User.Identity.Name, true).FullName;
                }
                catch
                {
                }
                var url = filterContext.HttpContext.Request.Url.ToString();
                var urlRef = filterContext.HttpContext.Request.UrlReferrer.PathAndQuery;
                var randStr = StringExtensions.GenerateRandomAlphaNumerics(new System.Random(), 4);
                Logger.Error(ex, "crashCode={0} - user={1} - url={2} - urlRef={3}", randStr, user, url, urlRef);
                filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                filterContext.ExceptionHandled = true;
                filterContext.Result = new RedirectResult("/misc/whoops?crash_code=" + randStr, true);
            }
        }
}

【问题讨论】:

    标签: asp.net-mvc redirect exception-handling unhandled-exception


    【解决方案1】:

    问题应该通过不将true传递给RedirectResult的第二个参数来解决。改为传递 false:

    filterContext.Result = new RedirectResult("/misc/whoops?crash_code=" + randStr, false);

    传递 true 作为第二个参数表示重定向是永久的。根据您的问题,这正是您不想要的。

    请参阅:MSDN RedirectResult301 vs 302 redirects

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-16
      • 2015-03-20
      • 2012-01-29
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多