Create a custom actionFilterAttribute like so (this example works from having your item stored in the session, but you could modify this as required):
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 an 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