2

私は、年次セッションに分割されたシステムに取り組んでいます。ユーザーはセッションに移動して変更し、過去のセッションを表示できます

yearId現在のユーザーをすべてのコントローラーに渡すにはどうすればよいですか?

認証時にユーザーの Cookie を設定できると考えていました。または、ユーザーが手動でセッションを変更し、そのようなグローバル フィルターを使用して Cookie を確認したときに、

public class MyTestAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpCookie cookie = filterContext.HttpContext.Request.Cookies["myCookie"];

        //do something with cookie.Value
        if (cookie!=null) 
        {
           filterContext.ActionParameters["YearId"] = cookie.Value;
        }
        else
        {
           // do something here
        }
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
    }
}

上記のフィルターを使用する方法は次のとおりです(またはグローバルフィルターとして追加します)。

[MyTestAttribute]
public ActionResult Index(int yearId)
{
    //Pass the yearId down the layers
    // _repo.GetData(yearId);
    return View();
}

このアプローチでは、すべてのコントローラーに yearId を追加する必要があります。フィードバックをお待ちしております。

4

2 に答える 2

1

フィルタではなく、パラメータを必要とするコントローラの基本クラスを作成することもできます。

public class MyBaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpCookie cookie = filterContext.HttpContext.Request.Cookies["myCookie"];

        //do something with cookie.Value
        if (cookie!=null) 
        {
           filterContext.ActionParameters["YearId"] = cookie.Value;
        }
        else
        {
           // do something here
        }
    }
}

または、厳密に型指定されたプロパティを作成して遅延させることもできます。これにより、すべてのアクションメソッドのパラメーターとしてそれを含める必要がなくなり、プロパティにアクセスしない限り評価を実行しません。

public class MyBaseController : Controller
{
    private int? _yearId;

    protected int YearId
    {
        get
        {
             // Only evaluate the first time the property is called
             if (!_yearId.HasValue)
             {
                 // HttpContext is accessible directly off of Controller
                 HttpCookie cookie = HttpContext.Request.Cookies["myCookie"];

                 //do something with cookie.Value
                 if (cookie!=null) 
                 {
                      _yearId = int.Parse(cookie.Value);
                 }
                 else
                 {
                      // do something here
                 }
             }

             return _yearId.Value;
        }
    }
}
于 2013-01-25T15:47:56.983 に答える
0

それはあまりにも多くのオーバーヘッドです。

セッションに値を入れてみませんか? 「セッション」を変更して過去のセッションを表示する場合は、セッションの変数を変更するだけです。

于 2013-01-25T14:42:38.743 に答える