Pomster
Pomster

Reputation: 15197

Custom RedirectToAction. Redirect from class?

I have a class running some function and on occasion an error occurs, i would like to redirect to my errorController but can't as this is in a separate classs.

Is there a way i could use redirectToAction or something similar to move to my errorContorller?

I tried this but could not redirect, it just run though the code and nothing happend.

public ActionResult Error(Dictionary<string, string> findError)
{
   TempData["Error"] = findError.Keys.First();
   TempData["ErrorMessage"] = findError.Values.First();
   return RedirectToAction("Error", "CustomError"); 
}

ErrorController:

namespace MvcResComm.Controllers
{
    public class CustomErrorController : Controller
    {
        //
        // GET: /Error/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Error()
        {
            string message = (string)TempData["ErrorMessage"];
            string ex = (string)TempData["Error"];
            ViewBag.Message = "Error";
            return View(new ErrorModel(ex, message));
        }
    }
}

Upvotes: 0

Views: 968

Answers (1)

SCV
SCV

Reputation: 251

This works for me.

Action Filter

public class HandleCustomErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
    {
        filterContext.ExceptionHandled = true;

            var routeData = new RouteData();
            routeData.Values["controller"] = "Controller Name";
            routeData.Values["action"] = "Action Method Name";
            routeData.DataTokens["area"] = "Area Name"; // Optional

            IController errorsController = new Controllers.ErrorController();
            var rc = new RequestContext(new HttpContextWrapper(HttpContext.Current), 
                                                                           routeData);
            errorsController.Execute(rc);

        base.OnException(filterContext);
    }
}

Now you can use this Action Filter for complete Controller or for the particular Action Method whereever you are facing issue(Controller level or Action method level).

Example

Controller Level

[HandleCustomError(Order = 5)]
public class MyController : Controller
{
}

This will be applied to all Action Methods of a Cont5roller.


Action method Level

public class MyController : Controller
{
     [HandleCustomError(Order = 5)]
     public ActionResult ActionMethod()
     {
         //Some code
     }   
}

This will be applied to particular Action Method of a Cont5roller.

Upvotes: 1

Related Questions