I want to get the UserName of the currently logged in User. But when I used User.Identity.Name I got following error:
System.NullReferenceException. Object reference not set to an instance of an object.
The code where I am getting the error is as follows:
UsersConfigurationController qr = new UsersConfigurationController();
public ActionResult Create(FormCollection collection)
{
try
{
context.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole()
{
Name = collection["RoleName"]
});
context.SaveChanges();
qr.singleRoleAddToDb(collection["RoleName"]);
ViewBag.ResultMessage = "Role created successfully !";
return RedirectToAction("Create");
}
catch
{
return View();
}
}
The error occurs when the following line is executed:
qr.singleRoleAddToDb(collection["RoleName"]);
The function singleRoleAddToDb resides in UserConfigurationController as follows:
public void singleRoleAddToDb(string rolename)
{
UserRoles urls = new UserRoles();
urls.S1 = rolename;
urls.S2 = HttpContext.User.Identity.Name;
urls.N102 = db.Users.Where(x => x.S1 == HttpContext.User.Identity.Name).Single().N102;
db.UserRoles.Add(urls);
db.SaveChanges();
}
As soon as the line urls.S2 = HttpContext.User.Identity.Name; executes the debugger switches to Catch statement and throws the above mentioned erro. I have already tried to change the authentication mode in config file:
<authentication mode="Forms" />
and also
<authentication mode="Windows" />
But the error continues.