简体   繁体   中英

How to stop execution process in MVC 5 with C#?

What line of code do I need in the TODO section?

My application code is:

/// <summary>
/// Override onAuthorization filter is use for authorization use request.
/// </summary>
/// <param name="filterContext"></param>

protected override void OnAuthorization(AuthorizationContext filterContext)
{
    AuthorizationManager authorizationManager = new AuthorizationManager();

    string FilePath = Convert.ToString(filterContext.HttpContext.Request.FilePath);

    if (!authorizationManager.IsAuthorized(_userSession, FilePath))
    {
        RedirectToControllers(ControllerHelper.Controller.ACCOUNT, ControllerHelper.Controller.Action.ACCOUNT_LOGIN);

        //TODO:
        // 1. Need to stop execution process from here. 
        // 2. No need to execute any line of code from here.
        // I have tested return/Break not working here.
    }
}

Change the RedirectToControllers to return an ActionResult then set the filterContext.Result .

//filterContext.Result = new RedirectResult("~/account/login");

filterContext.Result =  RedirectToControllers(ControllerHelper.Controller.ACCOUNT,  ControllerHelper.Controller.Action.ACCOUNT_LOGIN);

Have you tried using break to get out of the if ?

protected override void OnAuthorization(AuthorizationContext filterContext)
{
    AuthorizationManager authorizationManager = new AuthorizationManager();

    string FilePath = Convert.ToString(filterContext.HttpContext.Request.FilePath);

    if (!authorizationManager.IsAuthorized(_userSession, FilePath))
    {
        RedirectToControllers(ControllerHelper.Controller.ACCOUNT, ControllerHelper.Controller.Action.ACCOUNT_LOGIN);

        break; // use this
        return; // or this
        // 1. Need to stop excution process from here. 
        // 2. No need to excute any line of code from here.
    }
 }

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