简体   繁体   中英

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?

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);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM