June 2, 2016

SharePoint 2013 - Unable to read Web.Config file in Event receiver

Generally, we use web.config file’s app settings section to keep configurable and application wide settings that an application requires in order to perform the task properly. This helps in easy maintenance and deployment of the application, because we can easily update the settings and verify without build and deployment.

Now we read the key value pairs from web.config file as follow:

I need to use these app settings in Item added Event receiver in SharePoint list. Though, the above code worked fine on local environment, but on production server, it gave exception.
"Object reference not set to an instance of an object"

In the Event receiver, the above code is unable to find and read the web.config app settings, you would've noticed that although code compiles and runs, this comes back null. Well, the very generic answer to why this is, is because the event handler isn't really running within the same context as a Web site that has direct access to the ConfigurationManager.

There is a simple solution for this issue, just change the approach of reading the web.config file.

Below is the method we have implemented to read the web.config file:
public static string GetAppSettingKeyValue(SPSite siteCollection, string key)
            System.Configuration.Configuration config;
            if (string.IsNullOrEmpty(siteCollection.WebApplication.Name))
                throw new ApplicationException("Web application name is empty!");
            config = WebConfigurationManager.OpenWebConfiguration("/", siteCollection.WebApplication.Name);
            AppSettingsSection appSettings = config.AppSettings;
            if (appSettings == null)
                throw new ApplicationException("Web.config appSettings section cannot be found!");
            if (appSettings.Settings[key] == null || string.IsNullOrEmpty(appSettings.Settings[key].Value))
                throw new ApplicationException("Key value cannot be read from settings of appSettings. Make sure this key and its value exist!");
            return appSettings.Settings[key].Value;

And then we just have to call the above method from event receiver’s events with necessary parameters to read the settings as below:
GetAppSettingKeyValue(new SPSite(properties.SiteId), key);

Here, first parameter is SPSite object and the second parameter is a app settings key, for which we need to read value from web.config file.

Thus all we need to do is, just change the approach of reading web.config file and we are done! Now, we can successfully read the app settings configuration.

If you have any questions you can reach out our SharePoint Consulting team here.

No comments:

Post a Comment