Getting SPContext inside an event receiver

I created an Event Receiver, but the problem is that I cannot get a link to SPContext : SPContext.Current returns null . I need to add some listings to the site. Does anyone have any idea how I can get this?

I also tried putting breakpoints inside the event receiver, but FeatureActivates never fires for any reason. What correct event should be used when the list is activated immediately after deployment?

+7
source share
3 answers

You cannot get SPContext inside handlers - this is by design. You must use the event properties passed as an argument to the handler to get a link to the current network, list item, etc. For example, in an activated component handler, you can do this as follows:

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

If the feature area is a site, then

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

I realized that the scope is important. If you deployed this function in the site area, then you can get the network using this line of code:

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

I know this thread is kind of old, but you should actually use:

 SPWeb web = properties.OpenWeb() 

in accordance with the best practices of SP: http://msdn.microsoft.com/en-us/library/ee724407.ASPX This ensures that you do not have objects for disposal and will not allow you to get an error when casting.

+2
source

All Articles