I'm trying to implement a global filter for error handling and started testing as follows:
public class MyHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
var exception = filterContext.Exception;
var controller = ((Controller)filterContext.Controller);
if (exception is DbEntityValidationException)
{
var dbEx = exception as DbEntityValidationException;
foreach (var ve in dbEx.EntityValidationErrors.SelectMany(x => x.ValidationErrors))
controller.ModelState.AddModelError(string.Empty, ve.ErrorMessage);
}
else
{
controller.TempData["ErrorMessage"] = exception.GetBaseException().Message;
}
var routeData = filterContext.RouteData;
var currentController = routeData.GetRequiredString("action");
var currentAction = routeData.GetRequiredString("controller");
filterContext.Result = new RedirectResult($"/{currentController}/{currentAction}");
}
}
At first, I want to see that EntityFramwork validation errors, which have passed the ModelState
checks on Actions
( if (ModelState.IsValid)
), are added in ModelState.
Otherwise I want to throw the error in TempData
.
For both I want the user to be redirected to the page from which he made the request, but I can not even set the Result
of the filterContext
: filterContext.Result = new RedirectResult($"/{currentController}/{currentAction}");
The filter is registered in FilterCondif.cs
and I can debug it.
From TempData I check for an error message and then present a custom message.
How do I redirect to the previous page?