SPSite site = new SPSite(SPContext.Current.Web.Url) vs SPContext.Current.Web.Site

后端 未结 3 1312
旧巷少年郎
旧巷少年郎 2021-02-02 15:17

Why do some SharePoint examples use

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
    ...
}

and not just simply?



        
3条回答
  •  太阳男子
    2021-02-02 16:18

    Dennis G is correct. Disposing the SPSite/SPWeb/etc is important but make sure you do not dispose the objects that are provided to you by the API directly. It's subtle but critical otherwise your response will never get generated or cause even thread abort situations. In my experience, if I need quick information on the SPSite or SPWeb property that I am sure available to the user context (either a content manager authorized user or anonymous), then using SPContext.Current.* object is great. Otherwise, use the RunWithElevatedPriveleges method to wrap your code and inside that lambda has the following pattern:

    SPSecurity.RunWithElevatedPrivileges(() =>
    {
      using (SPSite site = new SPSite(SPContext.Current.Site.ID))
      {
        using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
        {
         // stuff goes here elevated
        }
      }
    });
    

提交回复
热议问题