2009-05-25 87 views
1

我正在使用MVC与C#。如果用户没有付款,我需要将用户带到付款页面。我需要有一个共同的类来检查这个功能并重定向到付款页面。未付款时重定向到页面

就像将所有控制器继承到基本控制器一样。在该基础控制器中,我必须检查某些控制器和操作(即ViewPage)的此付款状态并重定向到付款页面。

请人建议要做到这一点

回答

1

创建自定义actionFilterAttribute像这样(这个例子从存储在会话中您的项目工作,但你可以修改此为必填项):

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"); 
    } 
} 

然后你就可以将属性简单地添加到所有的控制器动作需要此检查:

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

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

RedirectToAction无法在CreatePaymentRequiredViewResult方法中访问。 – Prasad 2009-05-26 16:38:05

1

我建议你最好的方式做到这一点与动作atrribute

0

创建自定义ActionFilter是最好的解决方案。您可以下载ASP.NET MVC源代码并查看System.Web.Mvc.AuthorizeAttribute类。我认为这对你来说是一个很好的起点。