1
I am 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 treat so that validation errors of Entityframwork, which have gone through the verification of the ModelState
in Actions
(if (ModelState.IsValid)
), are added in the Modelstate.
Otherwise I want to play the bug on TempData
.
For both I want the user to be redirected to the page from which he made the request, but I’m not getting even setting the Result
of filterContext
: filterContext.Result = new RedirectResult($"/{currentController}/{currentAction}");
The filter is registered in FilterCondif.cs
and I can thresh it.
From Tempdata I check for error message and then present a custom message.
How can I redirect to the previous page?
I think the problem is not so much with picking up the url, I even put it manually, although I saw that its example is working correctly (I just needed to implement Iactionfilter instead of Iresultfilter - I don’t know why). And I’m still being redirected to the standard IIS error page.
– JamesTK
There is a View standard for errors. I can still improve the answer. If it’s of interest to you, add.
– Leonel Sanches da Silva
I would like to! I really need to go back to the previous View.
– JamesTK
I mean, I want to go back to the View that made the request. So I can show the model errors in the
ValidationSummary
or the custom error message (alert).– JamesTK
So, then I guess you’re going the wrong way.
HandleErrorAttribute
does not serve to treat validation, because a validation error is different from an application error. An application error cannot produce the same View that a normal flow. It asks for a View just for him. If you want, I can produce a second answer with the right path.– Leonel Sanches da Silva
Please, I would like yes in the right way! Thank you very much!
– JamesTK