【问题标题】:How do you change the redirect View of an ExceptionContext custom attribute?如何更改 ExceptionContext 自定义属性的重定向视图?
【发布时间】:2016-07-21 13:19:15
【问题描述】:

我有一个带有以下代码的自定义属性:

public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
        {
            //If customError is Off, then AI HTTPModule will report the exception
            if (filterContext.HttpContext.IsCustomErrorEnabled)
            {   
                      //Log to AI
            }
        }

        base.OnException(filterContext);
    }

因此,每当发生异常时,它都会通过此属性运行,该属性会将异常记录在 Application Insights 中。

我的问题是 base.OnException 正在重定向到默认的“错误”视图,我删除了位于 /Shared/Error.cshtml 中的默认错误视图,并创建了我自己的错误视图。如何让它重定向到我的自定义错误视图而不是默认视图?现在它正在抛出视图错误,因为它找不到默认的错误视图。

System.InvalidOperationException 未找到视图“错误”或其主视图,或者没有视图引擎支持搜索到的位置。搜索了以下位置:~/Views/Shared/Error.aspx ~/Views/Shared/Error.ascx ~/Views/Shared/Error.cshtml ~/Views/Shared/Error.vbhtml

对此的任何见解将不胜感激。谢谢!

【问题讨论】:

  • 为什么要使用另一个文件?只需更改默认Error.cshtml的内容
  • 我将其保存为我的最后一个选项,我不想这样做的原因是因为我们使用太多新的自定义错误页面,我不得不在任何地方进行更改。我还考虑添加它并将新的错误页面作为部分内容包含在内,但也不喜欢该选项。

标签: c# asp.net-mvc


【解决方案1】:

考虑以下选项:

1-Error.cshtml文件名不用改,文件内容可以改。

2-您可以通过这种方式将视图名称传递给您的自定义属性,并使用此属性装饰动作或控制器:

[CustomHandleError(View="SomeView")]

3- 如果您不想传递视图名称并且希望将名称放在中心位置,则可以这样编写自定义属性并使用[CustomHandleError]:

public class CustomHandleError:HandleErrorAttribute
{
    public CustomHandleError():base()
    {
        View = "SomeView";
    }
    //rest of your implementation
}

【讨论】:

    【解决方案2】:

    您可以在过滤器上下文中更新重定向结果

    filterContext.Result = this.RedirectToAction("YourErrorView", "YourErrorController");
    
     base.OnException(filterContext)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 2013-09-01
      • 1970-01-01
      相关资源
      最近更新 更多