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?
Custom attributes. A custom attribute is a property that you can define to describe assets. Custom attributes extend the meaning of an asset beyond what you can define with the standard attributes. You can create a custom attribute and assign to it a value that is an integer, a range of integers, or a string.
Declaring Custom AttributesWe can define an attribute by creating a class. This class should inherit from the Attribute class. Microsoft recommends appending the 'Attribute' suffix to the end of the class's name. After that, each property of our derived class will be a parameter of the desired data type.
Which of the following are correct ways to specify the targets for a custom attribute? A. By applying AttributeUsage to the custom attribute's class definition.
AttributeUsage has a named parameter, AllowMultiple , with which you can make a custom attribute single-use or multiuse. In the following code example, a multiuse attribute is created. In the following code example, multiple attributes of the same type are applied to a class. [Author("P.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With