Custom Attribute above a controller function

泄露秘密 提交于 2019-12-03 06:05:26

Sure. Do something like

public class FirstTimeAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(filterContext.HttpContext.Session != null)
        {
          var user = filterContext.HttpContext.Session["User"] as User;
          if(user != null && string.IsNullOrEmpty(user.FirstName))
              filterContext.Result = new RedirectResult("/home/firstname");
          else
          {
              //what ever you want, or nothing at all
          }
         }
    }
}

And just use [FirstTime] attribute on your actions

Attribute code:

  public class FirstTimeAttribute : ActionFilterAttribute, IActionFilter
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                if (string.IsNullOrEmpty(filterContext.HttpContext.Request[name]))
                {
                    filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary
                                            {
                                                { "controller", "Home" },
                                                { "action", "FirstTime" },
                                                { "area", string.Empty }
                                            });
                }
            }
   }

Usage:

[FirstTime]
public ActionResult Index(string name)
{
    return View();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!