Tuesday, 3 January 2012

MVC Update User Online via Action Filter

Action filter to update the currently logged in users last online time to allow you to identify which of your users are online

/// <summary>
/// User Online Action Filter Attribute
/// </summary>
public class UserOnlineActionFilterAttribute : ActionFilterAttribute
{
/// <summary>
/// Called by the ASP.NET MVC framework after the action method executes.
/// </summary>
/// <param name="filterContext">The filter context.</param>
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
try
{
if (filterContext.HttpContext != null && filterContext.HttpContext.User != null && filterContext.HttpContext.User.Identity != null)
{
Membership.Provider.GetUser(filterContext.HttpContext.User.Identity.Name, true);
}
}
catch
{
// BAD: Swallow the exception to prevent it messing with the users action
}

base.OnActionExecuted(filterContext);
}
}



Add the action filter to the global list inside the global.asax Application_Start.

GlobalFilters.Filters.Add(new UserOnlineActionFilterAttribute());

No comments:

Post a Comment