简体   繁体   中英

C#, ASP.NET how to call method during each call of any method of my Controller

How I can call method, for example checkouth() eveytime when user enter on Controller's page For example I have a few ActionResults - Create,Edit,Details,Orders and Index. Is it possible to call my method ( checkouth() ) before calling of methods from Contoller? It is required to check user access and redirect to another page.

You can define your action filter for that

public class CheckouthAttribute : ActionFilterAttribute, IResultFilter
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
         new RouteValueDictionary{{"controller", "Home" }, { "action", "Error" }});
    }
}

[Checkouth]
public ActionResult Index()
{
    return View();
}

Update: Now It will redirect to Error Action. Return view also possible:

  public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Result = new ViewResult
        {
            ViewName = "Error",
            ViewData = filterContext.Controller.ViewData
        };
    }

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