title: ASP.NET (OWIN) Identity: How to get UserID from a Web API controller?
body: <p>(Using VS2013 RTW, ASP.NET MVC5)</p>
  
  <p>I've seen lots of documentation on how to add properties to the ApplicationUser class (and table) when using ASP.NET identity. But I haven't seen any documentation on how to have a separate table with content that maps to the ApplicationUser table via a foreign key.</p>
  
  <p>I've successfully derived my own Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext, and now my own "UserPreferences" table coexists in harmony with the various "AspNet*" tables in my SQL Server database. But I'm not clear on the best way to get the current user's ID so as to write a new row to the "UserPreferences" table. Note that the project is ASP.NET MVC, but I've added (and am working inside of) a Web API controller. </p>
  
  <p>I have a working solution, which is:</p>
  
  <pre><code>            var uman = new Microsoft.AspNet.Identity.UserManager&lt;Microsoft.AspNet.Identity.EntityFramework.IdentityUser&gt;(new Microsoft.AspNet.Identity.EntityFramework.UserStore&lt;Microsoft.AspNet.Identity.EntityFramework.IdentityUser&gt;(new App1.Data.App1DbContext()));
  
              var uident = User.Identity;
  
              var userobject = uman.FindByNameAsync(uident.Name);
  
              var userid = userobject.Result.Id;
              // (Perform new row creation including the userid we just looked up
  </code></pre>
  
  <p>Consider that the AspNetUsers table (as defined by the Identity framework) consists of these fields:</p>
  
  <pre><code>-id (PK, nvarchar(128) - seems to contain a GUID, not sure why not an autoincrement integer, but I assume there are reasons for this)
  -Username (nvarchar(max))
  -PasswordHash (nvarchar(max))
  -SecurityStamp (nvarchar(max))
  </code></pre>
  
  <p>I think that the id field (not the username) is the correct field to reference in this table. (I was thinking that a user may change his/her username, and someone else could then assume the other user's username, which is why both fields are there likely.) So then, I need to get the current user's ID for storage in the "UserPreferences" table, which is what the above code does. But it seems inefficient to have to do this lookup.</p>
  
  <p>An important point is that in the context of a System.Web.Mvc.Controller, I can do:</p>
  
  <pre><code>User.Identity.GetUserId()
  (Runtime type of User.Identity: System.Security.Principal.GenericIdentity)
  </code></pre>
  
  <p>But in the context of a System.Web.Http.ApiController (Web API), I cannot because that method does not exist (runtime type of User.Identity: System.Security.Claims.ClaimsIdentity) which is why I must rely instead on:</p>
  
  <pre><code>User.Identity.Name
  </code></pre>
  
  <p>and do the extra lookup to convert Name to ID. Does anyone have any suggestions for how this can be improved? Am I approaching the task of writing user data to separate tables in the correct way?</p>