ASP.Net MVC 4 Using an Attribute or BaseController?

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

so something like this:

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

Can this be done in the Attribute and applies to the entire set of controller actions?

+6
source share
4 answers

An action filter is the way to go in this case:

An action filter that completes an action method. This filter may perform additional processing, such as providing additional data for the action method, checking the return value, or aborting the execution of the action method.

Here is a good MSDN How to: How to create a custom action filter

In your case, you will have something like this:

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

Then you apply this filter at 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 ... } 
+5
source

Yes.

Understanding action filters

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

(And you can also make it global for the entire application).

+2
source

It should be unsuccessful, and MS docs have a very nice walkthrough:

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

+1
source

Yes. You can use the action filter and change the result. Here is a simple attribute that will do something like this:

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

You can also override OnActionExecuted on the controller in a very similar way.

+1
source

All Articles