Ian Vink
Ian Vink

Reputation: 68750

ASP.Net MVC 4 Use of Attribute or BaseController?

I have a controller with several actions. The Action should be redirected if the IsCat field on a service is false:

so something like this:

    public ActionResult MyCatAction()
    {
        if (MyService.IsCat==false)
            return RedirectToAnotherControllerAction();
     ...

Can this be done in an Attribute and applied to the entire Controller's set of Actions?

Upvotes: 6

Views: 3746

Answers (4)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102408

Action filter is the way to go in this case:

Action filter, which wraps the action method execution. This filter can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method.

Here's a nice MSDN How To: How to: Create a Custom Action Filter

In your case, you'd have something like this:

public class RedirectFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (MyService.IsCat==false)
            return RedirectToAnotherControllerAction();
    }
}

Then, you'd apply this filter on the controller level (apply to all controller actions)

[RedirectFilterAttribute]
public class MyController : Controller
{
   // Will apply the filter to all actions inside this controller.

    public ActionResult MyCatAction()
    {

    }    
}

or per action:

[RedirectFilterAttribute]
public ActionResult MyCatAction()
{
     // Action logic
     ...
}    

Upvotes: 5

andypaxo
andypaxo

Reputation: 6621

Yes. You can use an action filter and modify the result. Here's a simple attribute that will do something like that:

public class RedirectOnCat : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if(MyService.IsCat == false)
            filterContext.Result = new RedirectResult(/* whatever you need here */);
    }
}

You could also override OnActionExecuted on the controller in a very similar manner.

Upvotes: 1

Alexei Levenkov
Alexei Levenkov

Reputation: 100537

Yes.

Understanding Action Filters

An action filter is an attribute. You can apply most action filters to either an individual controller action or an entire controller

(And you also can make it global to whole application).

Upvotes: 2

Tallmaris
Tallmaris

Reputation: 7590

It should be failrly straightforward to do, and the MS docs have a very nice walkthrough:

http://msdn.microsoft.com/en-us/library/dd381609(v=vs.100).aspx

Upvotes: 1

Related Questions