Set HttpContext.User for the session

Abdulsattar Mohammed picture Abdulsattar Mohammed · Jan 24, 2010 · Viewed 9.8k times · Source

I've implemented custom authentication in ASP.NET MVC. If a valid user tries to login, I set the HttpContext.User = user in the Logon method of the AccountController. But it remains there for only that request. How can I set it for the session?

I used an alternative, set HttpContext.Session["CurrentUser"] = user. If I want to see if the session is authorized, I'd have to check that the HttpContext.User != null. But, I don't want to expose the authentication logic everywhere in the application. If I need to change that, it'd be messy.

Please help me solve this. One solution could be populating the HttpContext.User property of every request with the value of HttpContext.Session["CurrentUser"] at the beginning, but I don't know how to do it.

Answer

Alex LE picture Alex LE · Jan 24, 2010

Write the following method in the Global.asax's Application class

protected void Application_BeginRequest(Object sender, EventArgs e)
{
   HttpContext.Current.User = HttpContext.Session["CurrentUser"];
}

or you can use the "User" property of System.Web.Mvc.Controller that is inherited to your controllers (note: be sure to call FormsAuthentication.SetAuthCookie method when successfully validate your user login).