asp.net-corecustom-attributesaction-filtercustom-action-filter

Is it possible to redirect to another action using a custom action filter?


I'm not familiar with ASP.NET Core actions' custom filter attribute. I need to redirect to another action in case some data does not exist using a custom method filter.

Here is my attempt:

[AttributeUsage(AttributeTargets.Class| AttributeTargets.Method, AllowMultiple = false)]
public class IsCompanyExistAttribute: ActionFilterAttribute
{
    private readonly ApplicationDbContext context;

    public IsCompanyExistAttribute(ApplicationDbContext context)
    {
        this.context = context;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //base.OnActionExecuting(filterContext);
        if (context.Companies == null)
        {
            return RedirectToAction(actionName: "Msg", controllerName: "Account", 
                new { message = "You are not allowed to register, since the company data not exist !!!" });
        }
    }

I didn't use filterContext. The RedirectToAction line appears as an error (with a red underline), of course, since it's a void method, not an action result. As I mentioned I'm not familiar with custom filters.

Any help, please?


Solution

  • Yes, it is. Simply set the Result property of the ActionExecutingContext instance to your RedirectToActionResult. It should look something like the following:

     public override void OnActionExecuting(ActionExecutingContext filterContext)
     {
         var controller = filterContext.Controller as ControllerBase; 
         if (context.Companies == null && controller != null)
         {
             filterContext.Result = controller.RedirectToAction(
                 actionName: "Msg", 
                 controllerName: "Account", 
                 new { message = "You are not allowed to register, since the company data not exist !!!" }
             );
         }
         base.OnActionExecuting(filterContext);
     }