【问题标题】:Getting SPContext inside event receiver在事件接收器中获取 SPContext
【发布时间】:2012-03-17 02:43:22
【问题描述】:

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

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

【问题讨论】:

    标签: c# sharepoint event-receiver spcontext


    【解决方案1】:

    您无法在处理程序中获取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
    }
    

    【讨论】:

      【解决方案2】:

      我认为功能的范围很重要。如果您在站点范围内部署了该功能,那么您可以使用这行代码获取网络:

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

      【讨论】:

        【解决方案3】:

        我知道这个帖子有点老了,但你真的应该使用:

        SPWeb web = properties.OpenWeb() 
        

        根据 SP 最佳实践:http://msdn.microsoft.com/en-us/library/ee724407.ASPX 它确保您没有要处理的对象,并防止您遇到铸造错误。

        【讨论】:

        • 这不适用于功能接收者。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多