Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 898
Ian Vink Avatar asked Mar 28 '13 15:03

Ian Vink


People also ask

What is the use of ActionName attribute?

ActionName attribute is an action selector which is used for a different name of the action method. We use ActionName attribute when we want that action method to be called with a different name instead of the actual name of the method.

What is the use of NonAction attribute in MVC?

The NonAction attribute is used when we want a public method in a controller but do not want to treat it as an action method. An action method is a public method in a controller that can be invoked using a URL. So, by default, if we have any public method in a controller then it can be invoked using a URL request.

What is the use of base controller in MVC?

The Controller in MVC architecture handles any incoming URL request. The Controller is a class, derived from the base class System. Web. Mvc.


1 Answers

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
     ...
}    
like image 180
Leniel Maccaferri Avatar answered Sep 21 '22 12:09

Leniel Maccaferri