天天看點

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;

    }

});

繼續閱讀