控制器功能上方的自定义属性

Gau*_*aui 11 c# custom-attributes asp.net-mvc-4

我想将[FirstTime]属性放在控制器函数之上,然后创建一个FirstTimeAttribute具有一些逻辑来检查用户是否输入了他的名字,并将其重定向到/Home/FirstTime他是否已经输入.

所以不要做:

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

    return View();
}
Run Code Online (Sandbox Code Playgroud)

我会这样做:

[FirstTime]
public ActionResult Index()
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Mih*_*hai 17

当然.做点什么

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
          }
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

只需对您的操作使用[FirstTime]属性即可