I wanted to reset the cache's twenty minutes to live, as specified in the example I give here, every time a user changed actions in an MVC Controller. I wanted to set up something AOPesque to do so. I'm not in love with what I have so far, but I have refactored my HomeController to inherit from a base controller called BaseController and look like this:
using System.Security.Principal;
using System.Web.Mvc;
using Security.Utilities;
namespace Security.Controllers
{
public class HomeController : BaseController
{
public ActionResult Index(string id)
{
Aop();
if (id != null)
{
GenericIdentity genericIdentity = new GenericIdentity(id);
GenericPrincipal genericPrincipal = new GenericPrincipal(genericIdentity, new
string[] { "User" });
IdentityUtility.SetIdentity(genericPrincipal, ViewBag.SessionKeyForIdentity);
}
return View();
}
}
}
Here is my base controller which every MVC Controller would inherit from and from which every MVC Controller Action would have to call the Aop method upon. This isn't too elegant. I wanted put this code inside an OnActionExecuting inside an ActionFilterAttribute, but it seems that session isn't available there. Boo.
using System;
using System.Threading;
using System.Web.Mvc;
using Security.Utilities;
namespace Security.Controllers
{
public class BaseController : Controller
{
protected void Aop()
{
string _sessionKeyForIdentity = "sessionkeyforidentity";
if (Session[_sessionKeyForIdentity] == null)
{
string randomString = RandomStringUtility.GetRandomString();
Session[_sessionKeyForIdentity] = randomString;
}
ViewBag.SessionKeyForIdentity = Session[_sessionKeyForIdentity] as String;
IdentityUtility.RefreshIdentity(ViewBag.SessionKeyForIdentity);
IdentityUtility.SetIdentity(Thread.CurrentPrincipal, ViewBag.SessionKeyForIdentity);
}
}
}
The attribute-based approach which I wasn't able to be working would have entailed setting up a class like this with some more substantive mechanics.
using System.Web.Mvc;
namespace Security.Utilities
{
public class MyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string breakpoint = "whatever";
}
}
}
No comments:
Post a Comment