0

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 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.