问题
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