2009-05-25 96 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類。我認爲這對你來說是一個很好的起點。