ASP NET MVC 2 - ASP.NET MVC Front Loading 12/24/2010 All ASP NET MVC 2 posts
One way to manage data retrieval and permission checks in MVC is to front load data objects into the HttpContext and work totally off of the Context from your Action Methods. If you have a standard set of route values you can accomplish this easily by overriding the OnAuthorization method in your Controller (or preferably in a base Controller that all of your controllers inherit from).
Now in your Action Methods you can simply reference CurrentUser and can always expect it to be populated since your base Controller has already found (or not found) and handled any bad data requests.
protected override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
string username = filterContext.RouteData.Values["username"] as string;
if (!string.IsNullOrEmpty(username))
{
CurrentUser = // Load User from BO, DAO, or whereever
if (CurrentUser == null)
{
// throw some exception or redirect because user doesn't exist
}
else
{
// check if this user is accessible by the logged in user or any other checks
}
}
}
public static User CurrentUser
{
get
{
return GetContextValue<User>("CurrentUser");
}
set
{
SetContextValue<User>("CurrentUser", value);
}
}