天天看点

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;

    }

});

继续阅读