在事件接收器中获取SPContext

时间:2012-02-27 16:09:05

标签: c# sharepoint event-receiver spcontext

我创建了一个事件接收器,但问题是我无法获得对SPContextSPContext.Current返回null的引用。我需要它来添加一些列表到网站。有谁知道我怎么能得到它?

此外,我尝试在事件接收器中放置断点,但FeatureActivates从未因某种原因触发。在部署之后立即激活列表时使用的正确事件是什么?

3 个答案:

答案 0 :(得分:15)

你无法获得SPContext内部处理程序 - 这是设计使然。您应该使用作为参数传递给处理程序的事件属性来获取对当前Web,列表项等的引用。 例如,在功能激活的处理程序中,您可以这样做:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPWeb web = properties.Feature.Parent as SPWeb;  
    //Some code with web
}

如果功能范围是网站,那么

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
        SPSite site = properties.Feature.Parent as SPSite;  
        //Some code with web
}

答案 1 :(得分:5)

我认为该功能的范围很重要。如果您在站点范围中部署了该功能,则可以使用以下代码行访问Web:

SPWeb web = (properties.Feature.Parent as SPSite).OpenWeb();

答案 2 :(得分:2)

我知道这个帖子有点陈旧,但你应该使用:

SPWeb web = properties.OpenWeb() 

根据SP最佳做法:http://msdn.microsoft.com/en-us/library/ee724407.ASPX 它可确保您无需处置任何对象,并防止出现施法错误。

相关问题