如何在用户通过身份验证后将变量传递给每个控制器

时间:2013-01-25 14:38:32

标签: c# asp.net-mvc asp.net-mvc-4

我正在开发一个分为年度会话的系统。用户可以去改变会话以查看过去的会话

我如何将用户当前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添加到每个控制器。任何反馈都表示赞赏。

2 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分:0)

这太过分了。

为什么不把值放在会话中?如果他们更改“会话”以查看过去的会话,只需修改会话中的变量。

相关问题