【发布时间】:2013-10-30 14:16:30
【问题描述】:
(使用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。有人对如何改进有任何建议吗?我是否正在以正确的方式将用户数据写入单独的表?
【问题讨论】:
-
注意:根据这篇文章:stackoverflow.com/questions/9768872/…“ApiController 有一个 System.Net.Http.HttpRequestMessage 类型的 Request 属性;这自然包含有关当前请求的详细信息(它还有一个 setter for unit测试目的)。HttpRequestMessage 有一个 Properties 字典;你会发现键 MS_UserPrincipal 的值保存了你的 IPrincipal 对象。但是“MS_UserPrincipal”不存在。我可以在字典的其他地方找到主体,但它返回与上面相同的对象,但不包含 ID...
标签: asp.net-mvc asp.net-web-api visual-studio-2013 owin asp.net-identity