简体   繁体   中英

How to prevent action execution in OnActionExecuting of class that is inhereted from the Controller

I need to check some conditions from request before action and decide whether to perform the action or not. I need this for all the actions of controller. For this, I make base controller inherited from standart MVC Controller class.

public abstract class BaseController : Controller
{
     public override void OnActionExecuting(ActionExecutingContext context)
     {

           //some code
           ...
           if(condition)
           {
             //not executeAction
           }
           base.OnActionExecuting(context);              

}

I have quickly found the answer. You need set Context.Result property. For instance.

public override void OnActionExecuting(ActionExecutingContext context)
{
        if(context.HttpContext.Request.Headers.ContainsKey("key"))
        {
            context.HttpContext.Response.StatusCode = 401;              
            NotExecuteAction = true;
        }



        if (NotExecuteAction)
        {
            context.Result = NoContent();
        }

        base.OnActionExecuting(context);           

}

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