在Asp MVC中显示静态数据类的自定义错误

问题描述 投票:0回答:1

Hello Stackoverflow人员,在我的mvc项目中,我有静态类,我在其中加载静态数据,然后在控制器中使用它。

  public  class StaticData
{
    public  static List<ITEM_TYPES> _itemTypes ;

    public static void LoadData()
    {
        try
        {
           using (pfservicereference.Service1Client ctx = new Service1Client())
            {
                _itemTypes = ctx.GetItemTypes();

            }
        }
        catch (Exception ex)
        {

            throw new HttpException(500,ex.Message);
        }

    }

}

但如何重定向到自定义错误页面如果我有HttpException在这里?

我已设置customErrors mode =“On”但它没有帮助。有没有办法重定向?

c# asp.net asp.net-mvc asp.net-mvc-4
1个回答
1
投票

您可以使用以下方法重定向到自定义错误页面,

方法1:

您可以在操作方法中使用try catch块并重定向到自定义错误页面。

    public ActionResult Index()
    {
        try
        {
             //Code logic here
        }
        catch (HttpException ex)
        {
            if (ex.ErrorCode == 500)
                return RedirectToAction("error", "error");
        }
        return View();
    }

方法2:

您可以根据我们可以重定向到自定义错误页面的错误代码,使用异常过滤器来捕获应用程序级别的错误。

对于此方法,您可以在global.asax或控制器级别创建单独的异常过滤器类和映射的应用程序级别。

    protected override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.Exception is HttpException)
        {
            HttpException exception = filterContext.Exception as HttpException;
            if (exception.ErrorCode == 600)
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
            {
                { "action", "Error" }, 
                { "controller", "Error" }
            });

            filterContext.ExceptionHandled = true;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.