Redirecting to a page when unpaid

I am using MVC from C #. I need to send a user to the checkout page if the user hasn't paid for the item. I need to have a generic class to test this functionality and redirect to the checkout page.

Like inheriting all controllers from the base controller. In this basic controller, I have to check this payment status for some controller and actions (i.e. ViewPage) and redirect to the payment page.

Please suggest a better way to do this

+1


a source to share


3 answers


Create your own actionFilterAttribute (for example, this example works if your element is stored in the session, but you can change it as needed):

public abstract class RequiresPaymentAttribute : ActionFilterAttribute
{
    protected bool ItemHasBeenPaidFor(Item item)
    {
        // insert your check here
    }

    private ActionExecutingContext actionContext;

    public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        this.actionContext = actionContext;

        if (ItemHasBeenPaidFor(GetItemFromSession()))
        {
            // Carry on with the request
            base.OnActionExecuting(actionContext);
        }            
        else
        {
            // Redirect to a payment required action
            actionContext.Result = CreatePaymentRequiredViewResult();
            actionContext.HttpContext.Response.Clear();
        }
    }

    private User GetItemFromSession()
    {
        return (Item)actionContext.HttpContext.Session["ItemSessionKey"];
    }

    private ActionResult CreatePaymentRequiredViewResult()
    {
        return new MyController().RedirectToAction("Required", "Payment");
    }
}

      



Then you can simply add the attribute to all controller actions that require this check:

public class MyController: Controller
{
    public RedirectToRouteResult RedirectToAction(string action, string controller)
    {
        return RedirectToAction(action, controller);
    }

    [RequiresPayment]
    public ActionResult Index()
    {
        // etc

      

+1


a source


I suggest you do it with the atrribute action



+1


a source


Making your custom ActionFilter is the best solution. You can download the ASP.NET MVC source and look at the System.Web.Mvc.AuthorizeAttribute class. I think this is a good starting point for you.

0


a source







All Articles