SharePoint如何模拟用户

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()      //用此方法模拟管理员账户运行此事件处理程序
                {
                    SPWeb web = SPContext.Current.Web;

                    //此时用户为sharepoint\system
                    //Response.Write("用户为:" + web.CurrentUser);

                    web.AllowUnsafeUpdates = true;

                    //获取到要模拟的用户的token    
                    SPUser user = web.EnsureUser("veekee\\user1");
                    SPUserToken token = user.UserToken;

                    //利用用户Token构造新的Site对象
                    SPSite siteWithUser = new SPSite(web.Url, token);

                    SPWeb webWidthUser = siteWithUser.RootWeb;

                    //此时用户为veekee\user1 
                    //Response.Write("用户为:" + webWidthUser.CurrentUser);
                    webWidthUser.AllowUnsafeUpdates = true;

                    //利用veekee\user1 用户来添加纪录
                    SPList list = webWidthUser.Lists["test1"];
                    SPListItem item = list.AddItem();
                    item["Title"] = "11";
                    item.Update();

                    webWidthUser.Dispose();
                    siteWithUser.Dispose();
                    web.Dispose();
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }

 

posted @ 2014-01-05 22:36  poisson_notes  阅读(930)  评论(0编辑  收藏  举报