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?
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.
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.
The Controller in MVC architecture handles any incoming URL request. The Controller is a class, derived from the base class System. Web. Mvc.
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
...
}
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