Thursday, 8 August 2013

ASP.NET MVC Is there a way to reuse code, instead of putting it in every Action?

ASP.NET MVC Is there a way to reuse code, instead of putting it in every
Action?

I made a functionality that prevents multiple-login for one username at
the same time and I call it in Actions like this:
int userId = (int)WebSecurity.CurrentUserId;
if ((this.Session.SessionID != dba.getSessionId(userId)) ||
dba.getSessionId(userId) == null)
{
WebSecurity.Logout();
return RedirectToAction("Index", "Home");
}
So the point is that every time user logins I save his sessionID into
database field. So if someone with same username logins over someone
already logged in with same username it overwrites that database field
with this new session. If sessionID in DB is not the same as current
session ID of logined user it log him out.
Is there a possibility to put this part of code in 1 place or do I have to
put it in every single Action in my application?
I tried in Global.asax:
void Application_BeginRequest(object sender, EventArgs e)
{
if (Session["ID"] != null)
{
int userId = Convert.ToInt32(Session["ID"]);
if ((this.Session.SessionID != db.getSessionId(userId)) ||
db.getSessionId(userId) == null)
{
WebSecurity.Logout();
}
}
}
But I can't use Session here nor WebSecurity class.
Thanks for any suggestions.

No comments:

Post a Comment