通过SPWeb.EnsureUser将SPUser添加到网站

最近在写代码时发现,通过Web.Users, Web.AllUsers,web. SiteUsers取得用户信息时经常找不到用户。

在项目中,域中有个组叫UK,这个组里有20多个人。当把UK这个组加到网站的访问者之后,UK组中的人都是可以通过自己的域账户来访问网站了。在代码中要取得用户的邮件,于是想到了用Web.Users来取得用户信息。但是通过调试发现,有几个用户总取不到信息,提示“未找到用户”。

取得用户信息可以用下面的语句:

SPWeb web = SPContext.Current.Web;
SPUser user = web.Users [“Domain\Username”];

如果该语句运行正常,就可以获取一个user对象。不幸的是,有几个用户总是找不到。于是尝试下面的语句,但结果同样是找不到用户。

SPUser user = web.AllUsers [“Domain\Username”];
SPUser user = web.SiteUsers [“Domain\Username”];

以下是MSDN对这三种方法的解释:

SPWeb.AllUsers
属性 (Microsoft.SharePoint)

Gets the collection of user objects that represents all users who are
either members of the site or who have browsed to the site as authenticated
members of a domain group in the site.

SPWeb.SiteUsers
属性 (Microsoft.SharePoint)

Gets the collection of all users that belong to the site collection.

SPWeb.Users
属性 (Microsoft.SharePoint)

Gets the collection of user objects that are explicitly assigned
permissions in the Web site. 

由此可见SPWeb.AllUsers取得的范围最大。根据我个人的理解要想成为members of the site,需要将该用户直接加入到网站中某一个用户组中,而不是加入其所在的域的组。所以此时即使用SPUser user = web. AllUsers [“Domain\Username”];也同样找不到用户。

解决的办法是用SPWeb.EnsureUser来检测一下用户是否存在。如果该用户不存在,这个方法会将该用户加到网站中。

SPWeb.EnsureUser
方法 (Microsoft.SharePoint)

Checks whether the specified login name belongs to a valid user of the Web
site, and if the login name does not already exist, adds it to the Web site. 

至此问题解决。

原文地址:https://www.cnblogs.com/masahiro/p/10128833.html