Linq to SharePoint与权限提升

SharePoint 2010支持Linq to SharePoint,让程序员可以使用Linq语法直接访问SharePoint 2010网站中的数据。但是在默认情况下,Linq to SharePoint不支持权限提升,也就是说,如果在代码中尝试通过SPSecurity.RunWithElevatedPrivileges()方法来提升执行权限,你可能会发现,代码并不会如你所愿的以系统帐户的身份,访问SharePoint网站的数据。

下面是一段典型的权限提升的代码,在匿名委托方法中,首先构造了新的SPSite和SPWeb对象,然后使用Linq to SharePoint查询了一个列表中所有列表项的标题。虽然看起来Linq to SharePoint好像会被提升它执行的权限,但实际情况并非如此。在下面的代码中,中间的Linq to SharePoint代码并不会受到外面调用SPSecurity.RunWithElevatedPrivileges()方法的影响。

private IEnumerable<String> GetAllHardwareNames() 
{ 
    var currentWebUrl = SPContext.Current.Web.Url; 
    List<String> result = null;

    SPSecurity.RunWithElevatedPrivileges(delegate() 
    { 
        using (var site = new SPSite(currentWebUrl)) 
        { 
            using (var web = site.OpenWeb()) 
            {
 
                using (var ctx = new ContosoDataContext(currentWebUrl)) 
                { 
                    var names = from h in ctx.硬件资产跟踪 
                                select h.标题; 
                    result = names.ToList(); 
                } 
            } 
        } 
    });

    return result; 
}

如果希望Linq to SharePoint代码能够提升它的执行权限,在使用Linq to SharePoint之前,需要做一个比较trick的事情,那就是将当前HttpContext对象设置为null。下面的代码中,使用粗体标识了这些特殊的代码。

SPSecurity.RunWithElevatedPrivileges(delegate() 
{ 
    using (var site = new SPSite(currentWebUrl)) 
    { 
        using (var web = site.OpenWeb()) 
        { 
            var httpContext = HttpContext.Current; 
            HttpContext.Current = null;

            using (var ctx = new ContosoDataContext(currentWebUrl)) 
            { 
                var names = from h in ctx.硬件资产跟踪 
                            select h.标题; 
                result = names.ToList(); 
            }

            HttpContext.Current = httpContext; 
        } 
    } 
});

只所以要使用这个技巧,是因为在Linq to SharePoint的实现中,使用了一个名为Microsoft.SharePoint.Linq.Provider.SPServerDataConnection的类,来真正连接到SharePoint网站。在这个类的构造函数中,有类似这样的代码:

if (SPContext.Current != null) 
{ 
    this.defaultSite = SPContext.Current.Site; 
    this.defaultWeb = (SPContext.Current.Web.Url == url) ? SPContext.Current.Web : this.defaultSite.OpenWeb(new Uri(url).PathAndQuery); 
} 
else 
{ 
    this.defaultSite = new SPSite(url); 
    this.defaultWeb = this.defaultSite.OpenWeb(new Uri(url).PathAndQuery); 
}

为了提高性能,它会优先重用SPContext对象中所缓存的SPWeb和SPSite对象。这个行为虽然可以提高代码的运行效率,但是却会导致权限提升的失效,因为提升了权限的代码必须使用一个新构造的SPSite和SPWeb对象。

原文地址:http://kaneboy.blog.51cto.com/1308893/769762

原文地址:https://www.cnblogs.com/xiaxianglanyu/p/3363728.html