ASP.NET (OWIN) 身份:如何從 Web API 控制器獲取使用者 ID?
(使用VS2013 RTW,ASP.NET MVC5)
我看過很多關於如何在使用 ASP.NET 標識時向 ApplicationUser 類(和表)添加屬性的文件。但是我還沒有看到任何關於如何擁有一個單獨的表的文件,該表的內容通過外鍵映射到 ApplicationUser 表。
我已經成功地派生了我自己的 Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext,現在我自己的“UserPreferences”表與我的 SQL Server 數據庫中的各種“AspNet*”表和諧共存。但我不清楚獲取目前使用者 ID 以便將新行寫入“UserPreferences”表的最佳方法。請注意,該項目是 ASP.NET MVC,但我已經添加(並且正在其中工作)一個 Web API 控制器。
我有一個可行的解決方案,即:
var uman = new Microsoft.AspNet.Identity.UserManager<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(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考慮 AspNetUsers 表(由 Identity 框架定義)由以下欄位組成:
-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))我認為 id 欄位(不是使用者名)是此表中要引用的正確欄位。(我在想一個使用者可能會更改他/她的使用者名,然後其他人可以假設另一個使用者的使用者名,這就是為什麼兩個欄位都可能存在的原因。)那麼,我需要獲取目前使用者的 ID 以儲存在“UserPreferences”表,這就是上面的程式碼所做的。但是必須進行此查找似乎效率低下。
重要的一點是,在 System.Web.Mvc.Controller 的上下文中,我可以這樣做:
User.Identity.GetUserId() (Runtime type of User.Identity: System.Security.Principal.GenericIdentity)但是在 System.Web.Http.ApiController (Web API) 的上下文中,我不能,因為該方法不存在(User.Identity 的執行時類型:System.Security.Claims.ClaimsIdentity),這就是我必須依賴的原因:
User.Identity.Name並進行額外的查找以將名稱轉換為 ID。有人對如何改進有任何建議嗎?我是否正在以正確的方式將使用者數據寫入單獨的表?
您應該能夠通過identity 1.0 RTW 包中的相同擴展方法在 MVC 控制器和 Web api 控制器上獲取使用者 ID 。
這是身份包的擴展:
namespace Microsoft.AspNet.Identity { public static class IdentityExtensions { public static string FindFirstValue(this ClaimsIdentity identity, string claimType); public static string GetUserId(this IIdentity identity); public static string GetUserName(this IIdentity identity); } }IIdentity 是所有身份類型的基本介面。您可能需要添加“使用 Microsoft.AspNet.Identity”才能查看擴展方法。
順便說一句:關於為使用者添加外部表,為什麼不使用 ApplicationUser 並將導航屬性添加到 UserPreference 以讓 EF 處理它們的關係?那會更容易。