Request/User object is null in Controller constructor in ASP.NET MVC

Posted by Sheonarayan under Error and Solution on 7/15/2014 | Points: 10 | Views : 16710 | Status : [Administrator] | Replies : 0


I was trying to access the User object in Controller constructor so that I can get the logged in username in the constructor, but the User object was coming as null and as a result I was getting Null reference exception.


The solution of this problem is to create an override method of Initialize by passing RequestContext object.
public class ChartsController : Controller
string _userName = string.Empty;
protected override void Initialize(System.Web.Routing.RequestContext requestContext)

if (requestContext.HttpContext.User.Identity.IsAuthenticated)
_userName = requestContext.HttpContext.User.Identity.Name;

and then we can access the User object. The same is applicable for Session or any other object inside HttpContext.

Hope this helps.


Sheo Narayan


(No response found.)

Login to post response