Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sharepoint SPSite site=新的SPSite(SPContext.Current.Web.Url)与SPContext.Current.Web.site_Sharepoint_Sharepoint 2010 - Fatal编程技术网

Sharepoint SPSite site=新的SPSite(SPContext.Current.Web.Url)与SPContext.Current.Web.site

Sharepoint SPSite site=新的SPSite(SPContext.Current.Web.Url)与SPContext.Current.Web.site,sharepoint,sharepoint-2010,Sharepoint,Sharepoint 2010,为什么有些SharePoint示例使用 using (SPSite site = new SPSite(SPContext.Current.Web.Url)) { ... } 不仅仅是简单 SPSite site = SPContext.Current.Web.Site; ... 更新 我想我已经把问题缩小到以下几个方面: 似乎我不应该直接使用SPContent.Current,除非我确定我的代码在SharePoint中运行。但是什么时候不是这样呢?这取决于代码运行的上下文。例如,如

为什么有些SharePoint示例使用

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
    ...
}
不仅仅是简单

SPSite site = SPContext.Current.Web.Site;
...
更新

我想我已经把问题缩小到以下几个方面:


似乎我不应该直接使用
SPContent.Current
,除非我确定我的代码在SharePoint中运行。但是什么时候不是这样呢?

这取决于代码运行的上下文。例如,如果您在
RunWithLevatedPrivileges
块中运行,则需要创建一个新的
SPSite
实例。

请查看Microsoft提供的关于的最佳实践文档,但是有

SharePoint项目有几个关键要点:

  • 始终处理您的SPWeb/SPSite对象-->内存泄漏
  • 使用SPContext.Current。。。当您确定代码正在SharePoint上下文中运行时
    • 单元测试意味着没有Sharepoint上下文
    • 外部实用程序意味着没有Sharepoint上下文
    • Powershell表示没有SharePoint上下文(例如,使用功能接收器激活功能可能失败)
  • 不处理SPContext.Current。。。但是创建您自己的对象(再次使用)
您可能有多个SP。。对象

最后
SPSite site=SPContext.Current.Web.site
在某些情况下很好,但您无法控制此
站点
对象-这可能就是问题所在。如果您选择
新SPSite(…)
,您将始终拥有您的
SPSite
,而不是SharePoint为您创建和管理的内容


就我个人而言,我几乎总是选择使用结构的
,这样之后所有对象都会得到正确的处理。或者,我使用
SPContext.Current.Web
而不进行处理。

Dennis G是正确的。处理SPSite/SPWeb/etc很重要,但请确保不要直接处理API提供给您的对象。这很微妙,但很关键,否则您的响应将永远不会生成,甚至不会导致线程中止情况。 根据我的经验,如果我需要有关SPSite或SPWeb属性的快速信息,并且我确信这些信息可供用户上下文(content manager授权用户或匿名用户)使用,那么使用SPContext.Current.*对象就很好了。否则,请使用runWithElevatedPrivileges方法包装代码,其中lambda具有以下模式:

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

看看我提出的一个类似问题:谢谢你的链接。我已经更新了我的问题。在更大的项目上,有时SharePoint中没有运行外部实用程序。另一个例子是单元测试,它也不在SharePoint中运行。如果您只是开发可视化Web部件,而不进行单元测试,那么您的代码将在SP中运行。当在代码中频繁使用时,新的SPSite/SPWeb似乎存在性能问题approach@moontear我想知道:如果我正在编写一个HttpModule,它是否在SharePoint中运行?这将是请求的一部分,但更多的是在IIS/Web应用程序级别,只是对您的意见/观察/等等感兴趣