title: Object Reference error for User.Identity.Name in MVC 5 Controller
body: <p>I want to get the UserName of the currently logged in User. But when I used <strong>User.Identity.Name</strong> I got following error:</p>
  
  <blockquote>
    <p>System.NullReferenceException. Object reference not set to an instance
    of an object.</p>
  </blockquote>
  
  <p>The code where I am getting the error is as follows:</p>
  
  <pre><code>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();
              }
          }
  </code></pre>
  
  <p>The error occurs when the following line is executed:</p>
  
  <blockquote>
    <p>qr.singleRoleAddToDb(collection["RoleName"]);</p>
  </blockquote>
  
  <p>The function <strong>singleRoleAddToDb</strong> resides in UserConfigurationController as follows:</p>
  
  <pre><code>public void singleRoleAddToDb(string rolename)
          {
              UserRoles urls = new UserRoles();
              urls.S1 = rolename;
              urls.S2 = HttpContext.User.Identity.Name;
              urls.N102 = db.Users.Where(x =&gt; x.S1 == HttpContext.User.Identity.Name).Single().N102;
              db.UserRoles.Add(urls);
              db.SaveChanges();
  
          }  
  </code></pre>
  
  <p>As soon as the line <strong>urls.S2 = HttpContext.User.Identity.Name;</strong> 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:</p>
  
  <pre><code>&lt;authentication mode="Forms" /&gt;
  </code></pre>
  
  <p>and also </p>
  
  <pre><code>&lt;authentication mode="Windows" /&gt;
  </code></pre>
  
  <p>But the error continues.</p>