简体   繁体   中英

How to redirect to view from global exception filter in Asp.Net MVC

I am working on a MVC using asp.net core where I have created a global filter to handling exceptions. Its handling exceptions but not redirecting to view(Error.cshtml) which is in Shared folder.

Below is my code:

public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled)
            {
                return;
            }
            Exception e = filterContext.Exception;
            filterContext.ExceptionHandled = true;
            string action = filterContext.RouteData.Values["action"].ToString();
            string controller = filterContext.RouteData.Values["controller"].ToString();
            filterContext.Result = new ViewResult()
            {
                ViewName = "/Error" // also tried with "Error" and "~/Error"
            };
        }

I hope this works for you

protected override void OnException(ExceptionContext filterContext)
{
  filterContext.ExceptionHandled = true;

  //Redirect or return a view, but not both.
  filterContext.Result = RedirectToAction("Index", "Home");
  // OR 
  filterContext.Result = new ViewResult
  {
     ViewName = "~/Views/Shared/Error.cshtml"
  };
}
        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary
            {
                { "controller", "Account" },
                { "action", "Index" },
                { "returnUrl", filterContext.HttpContext.Request.RawUrl } 
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM