CR41G14
CR41G14

Reputation: 5594

Check if a user is online mvc4

I am using MVC4 and what I want to be able to do is to check the status of a user's friend to see whether they are online or not for chat purposes. I have explored the WebSecurity and MEmebership classes but cannot see any functionality within these. Do I have to do something with getting the sessions from the IIS server?

Thanks in advance

Upvotes: 3

Views: 1778

Answers (2)

Nikolay Kostov
Nikolay Kostov

Reputation: 16983

One possible solution I am suggesting you is to create a global filter that populates LastActionTime field of every user and then use this field to determine whether the user is online or not:

First create a new property of type DateTime? called LastActionTime in your User class in case you are using Code-First approach. In case you are using Database-First approach just add nullable DateTime column in you Users table and update your local model.

public class User
{
    // ...
    public DateTime? LastActionTime { get; set; }
    // ...
}

Then create a new class called LogUserActionTimeFilter and implement it's OnActionExecuting and OnActionExecuted method. If you have any services or DbContexts, initialize them in the constructor of the class.

public class LogUserActionTimeFilter : IActionFilter
{
    private readonly IUserAuthService userAuthService;

    public LogAdminRequestFilter()
        : this(new UserAuthService())
    {
    }

    public LogAdminRequestFilter(IUserAuthService userAuthService)
    {
        this.userAuthService = userAuthService;
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        this.userAuthService.SaveCurrentTimeAsLastActionTime(
            filterContext.HttpContext.User.Identity.Name);
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
    }
}

The SaveCurrentTimeAsLastActionTime method just sets LastActionTime to DateTime.Now of the given user and saves changes. It should be easy to implement.

When done with the filter you can apply it to specific actions, controllers (e.g. in the chat only) or globaly:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new LogUserActionTimeFilter());
    }
}

When you need to determine if a user is online or not just check its LastActionTime column/property and if it is less than 5 minutes (for example) before DateTime.Now then the user may be considered online.

Upvotes: 3

Amr Elgarhy
Amr Elgarhy

Reputation: 69052

There is MembershipUser.IsOnline Property but if this is not useful you can use signlR to check the current status and may be store it somewhere.
Else you can do an ajax call every few minutes to check user status and also store it somewhere.

Upvotes: 3

Related Questions