Custom Attribute above a controller function

故事扮演 提交于 2019-12-04 10:44:07

问题


I want to put [FirstTime] attribute above a controller function and then create a FirstTimeAttribute that has some logic that checks whether the user has entered his name, and redirects him to /Home/FirstTime if he hasn't.

So Instead of doing:

public ActionResult Index()
{
    // Some major logic here
    if (...)
        return RedirectToAction("FirstTime", "Home");

    return View();
}

I would just do:

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

Is this possible?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/13310112/custom-attribute-above-a-controller-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!