I am working on a system that is segmented into yearly sessions. A user can go and change the session to see past sessions
How would I go about passing the users current yearId to every controller?
I was thinking that I could set a users cookie on authentication or when they manually change their session and check the cookie using a global filter like so
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);
}
}
Here’s how I’d use the above filter: (or add it as a global filter)
[MyTestAttribute]
public ActionResult Index(int yearId)
{
//Pass the yearId down the layers
// _repo.GetData(yearId);
return View();
}
With this approach, I would have to add yearId to every controller. Any feedback is appreciated.
You could also create a base class for your Controllers that need the parameter as opposed to the filter:
Or you could even create a strongly-typed property and make it lazy, so that you don’t have to include it as a parameter to every action method and don’t perform the evaluation unless you access the property: