2009-05-25 12 views
1

私はC#でMVCを使用しています。ユーザーがアイテムを支払っていない場合、ユーザーを支払いページに連れて行く必要があります。この機能をチェックして支払いページにリダイレクトする共通のクラスが必要です。未払いの場合はページにリダイレクト

すべてのコントローラをベースコントローラに継承しているような感じです。そのベースコントローラーでは、私はいくつかのコントローラーとアクション(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

CreatePaymentRequiredViewResultメソッドでは、RedirectToActionにアクセスできません。 – Prasad

+0

ええ、私は、その例の生産コードを変更したとき、あまり単純化したかもしれません。私の例を更新しています... –

1

を行うための最善の方法を提案してください、私はあなたが

0

は、カスタムのActionFilterを作成atrributeアクションでこれを行う提案は、最適なソリューションです。 ASP.NET MVCソースをダウンロードし、System.Web.Mvc.AuthorizeAttributeクラスを見ることができます。私はそれがあなたにとって良い出発点だと思う。

関連する問題