Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Attribute above a controller function

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?

like image 696
Gaui Avatar asked Nov 09 '12 14:11

Gaui


People also ask

What are custom attributes?

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.

How do I create a custom attribute in .NET core?

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.

How can you specify a target for a custom attribute?

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.

How do I add custom attributes to my framework?

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.


1 Answers

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

like image 146
Mihai Avatar answered Sep 17 '22 21:09

Mihai