How to redirect from OnActionExecution to an Action in a controller (Asp.net core 5)

1k views Asked by At

Hi guys I’m working on an Asp.net core project targeted .Net 5

I created a class inherited from IActionFilter and I used the OnActionExecution method I did some logic in it and wanna redirect from it to another Action in a Controller.

The problem : The problem is how can I redirect to the action that request came from and I tried many solution depending on my knowledge but no one succeeds.

What I tried :

       public class ValidationFilterAttribute : IActionFilter
        {
            public void OnActionExecuting(ActionExecutingContext context)
            {
                
 //some logic to get the model
                if(!context.ModelState.IsValid)
                {
                    Context.Result = new RedirectToAction(“Idon’t know how to get action”, “I don’t know how to get controller”,new{model= /*model I got*/});
                }
            }
            public void OnActionExecuted(ActionExecutedContext context)
            {          
            }
        }

Question : I have two questions,

  1. How to know the Action and the Controller names that request came from ?
  2. How can I redirect to the same Action but in the same Controller and send the same model gotten in ‘OnActionExecution’

Why I do that : My Idea is using my own ‘IActionFilter’ class with any method worked in HttpPost To check if the model sent is valid or not and if not valid On OnActionExecution method will add errors to the model and resent it again to the action.

Please any help about this issue ?

1

There are 1 answers

6
Anton Kovachev On

You can define a custom ActionFilter like this

    public class ValidationFilterAttribute : ActionFilterAttribute
    {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                 var controllerName =  filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; // Get controller name

                 var modelState = (filterContext.Controller. as Controller).ViewData.ModelState; // Get the model state of the request
                 var model = (filterContext.Controller as Controller).ViewData.Model; // Get the model of the request

                 //do your stuff here

                  base.OnActionExecuting(filterContext);
             }
       }

And then register your filter so it will be applied to every controller and every action in your project

public void ConfigureServices(IServiceCollection services)
{
     services.AddMvcCore(options =>
     {
         options.Filters.Add(typeof(ValidationFilterAttribute));
     });
 }

This way before hitting the controller's action method body each request will pass through your ValidationFilterAttribute where you can examine his Model and change his ModelState.