以编程方式将声明添加到列表中

时间:2011-10-26 07:11:26

标签: sharepoint-2010 claims-based-identity

我写了一小段代码,在Sharepoint中添加对网站的声明。 我继续这样做:

using (SPSite site = new SPSite(url)) 
        { 
            using (SPWeb web = site.OpenWeb())
            { 
                SPClaimProviderManager claimMgr = SPClaimProviderManager.Local; 
                if (claimMgr != null) 
                {
                    SPClaim claim = new SPClaim(type, claim_name, Microsoft.IdentityModel.Claims.ClaimValueTypes.String, SPOriginalIssuers.Format(SPOriginalIssuerType.ClaimProvider, provider)); 
                    string userName = claimMgr.EncodeClaim(claim); 
                    SPUserInfo info = new SPUserInfo 
                    { LoginName = userName, 
                        Name = name }; 

                    SPRoleAssignment roleAssignment = new SPRoleAssignment(info.LoginName, info.Email, info.Name, info.Notes); 
                    roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions["Read"]); 
                    web.RoleAssignments.Add(roleAssignment); 
                    web.Update(); 
                } 
            } 
        } 

非常简单,但我想将声明添加到我创建的列表中。到现在为止,我正在使用SPSite和SPWeb访问该网站,但我需要更深入:)我找不到办法...

提前谢谢!

1 个答案:

答案 0 :(得分:1)

由于SPWebSPList都继承自SPSecurableObject所有您需要做的就是为要更改权限的列表加载SPList对象。

可以by URLlist title加载SPList

SPList listByTitle = web.Lists["Tasks"];
SPList listByUrl = web.GetList("/server/relative/Lists/Tasks");

在你的例子中:

        using (SPSite site = new SPSite(url)) 
        { 
            using (SPWeb web = site.OpenWeb())
            { 
                SPClaimProviderManager claimMgr = SPClaimProviderManager.Local; 
                if (claimMgr != null) 
                {
                    SPClaim claim = new SPClaim(type, claim_name, Microsoft.IdentityModel.Claims.ClaimValueTypes.String, SPOriginalIssuers.Format(SPOriginalIssuerType.ClaimProvider, provider)); 
                    string userName = claimMgr.EncodeClaim(claim); 
                    SPUserInfo info = new SPUserInfo 
                    { LoginName = userName, 
                        Name = name }; 

                    SPRoleAssignment roleAssignment = new SPRoleAssignment(info.LoginName, info.Email, info.Name, info.Notes); 
                    roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions["Read"]); 
                    // web.RoleAssignments.Add(roleAssignment); 
                    // web.Update(); 

                    SPList list = web.Lists["TheListTitle"];
                    list.RoleAssignments.Add(roleAssignment);
                } 
            } 
        } 

修改角色分配后,无需更新网页或列表。