'Keep ModelState After Redirect inside ExceptionFilterAttribute

I have a Mediatr pipeline behaviour which handles validation as a cross cutting concern, using FluentValidation it throws a ValidationException containing the validation errors. This saves me having to have ModelState.IsValid on every action. (Lets ignore that it uses an exception for flow control at the moment, it's a trade off I can accept).

So now, if there is a validation error, I have a ValidationException to handle. I do not want to have try{}catch{} in all of my actions either, so I am creating an ExceptionFilterAttribute to handle the validation exception.

Currently it looks as shown below. I am grabbing the errors and merging them into the ModelState. I then somehow have to get back to the page to make use of the ModelState and show the errors nicely.

The only way I can see how to do that would be a RedirectToRouteResult but of course this will cause me to lose the ModelState.

Is there a way to maintain ModelState for the redirect or return to the page from here? So far I cannot see a way to do it.

    public class ValidationExceptionHandlerFilter : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {            
            if(context.Exception is ValidationException)
            {
                context.ExceptionHandled = true;
                ValidationException vEx = (ValidationException)context.Exception;
                ModelStateDictionary msd = new ModelStateDictionary();

                foreach (var err in vEx.Errors)
                {
                    msd.AddModelError(err.PropertyName, err.ErrorMessage);
                }

                context.ModelState.Merge(msd);

                context.Result = new RedirectToRouteResult(context.HttpContext.Request.Path);
            }

            base.OnException(context);
        }
    }

//edit

I have changed to using /ExceptionFilter rather than ExceptionFilterAttribute since its an expected exception, but the issue remains of how to maintain ModelState



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source