Using the SharePoint Object Model in WebPart Constructor Causes Security Exception

Writing a web part recently, I was attempting to set some default values for locale sensitive properties. I wanted them set early in the webpart lifecycle so I figured I’d do it in the web part constructor.

Since they are locale sensitive I was using the SPUtility.GeLocalizedString method to fetch the value from resources.

When I tried adding the web part to a page, I’d get a security exception which indicated that “access to the file is denied”. Among other things the exception also contained various security link demand violations.

Thanks to an obscure post I found on a forum somewhere, it turns out that you can’t call the SharePoint object model from the constructor, and moving the offending calls to another location (say OnInit) fixed the problem.

Published by

Phil Harding

SharePoint Consultant, Developer, Father, Husband and Climber.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.