0
votes

Say I have a controller with multiple actions, is there an override to make the controller return a default action if a condition is met?

Example:

I have a checkoutcontroller and I want each action to return HttpNotFound() if e-commerce is disabled on the site, is there a better way of doing it than just doing the following:

public class CheckoutController
{
    [HttpGet]
    public ActionResult ViewBasket()
    {
        if (AppSettings.EcommerceEnabled)
        {
            return View();
        }
        else
        {
            return HttpNotFound();
        }
    }

    [HttpGet]
    public ActionResult DeliveryAddress()
    {
        if (AppSettings.EcommerceEnabled)
        {
            return View();
        }
        else
        {
            return HttpNotFound();
        }
    }
}
2

2 Answers

2
votes

You can create a custom action filter that will be used for action methods inside CheckoutController.

public class CommercePermissionAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (AppSettings.EcommerceEnabled)
        {
            base.OnActionExecuting(filterContext);
        }
        else
        {
           // Example for redirection
           filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary 
                { 
                    { "Controller", "Error" }, 
                    { "Action", "AccessDenied" }
                });
        }  
    }
}

Then you can use this filter on each action method by

[HttpGet]
[CommercePermission]
public ActionResult ViewBasket()

Or if you want whole controller actions to have this filter,

[CommercePermission]
public class CheckoutController

You can even apply filters globally to all actions in your project.

You can find more info here.

0
votes

You could create a custom action filter. This would intercept the routing to that action, apply its internal logic, and either continue to the action or interrupt it as you define in the filter. Filters can be applied to individual actions, an entire controller class, or even globally for the whole application.