Accessing termstore in Feature Receiver throws UnauthorizedAccessException
-
29-09-2020 - |
Frage
Im trying to run the code below but I get a UnauthorizedAccessException
at the last line(using SP 2013)
TaxonomySession newTaxonomySession = new TaxonomySession(site);
var termStore = newTaxonomySession.DefaultSiteCollectionTermStore;
var siteCollectionGroup = termStore.GetSiteCollectionGroup(site);// <-- throws UnauthorizedAccessException
- I have wrapped the code in
RunWithElevatedPrivileges
- User xxx is farm admin
- Added user xxx to Managed Metadata admin in CA, also as Term Store administrators, Group Manager for the term group and owner of term set
- I am logged in as xxx and also tried to impersonate xxx (new
SPSite
(url, userToken)) - I am able to activate feature in SP GUI without problems
- I Have verified through logging that the
web.CurrentUser.LoginName
is xxx - I have also tried to set
HttpContext.Current = null
Before the code above
Details:
I'm stapling the feature to SPSPERS
Template (my sites-sitecoll), so the feature receiver code (above) is run when a new personal site coll. is created.
Lösung
It turns out that I'll get the above error if "Publishing Infrastructure" is not activated on the site coll... a bit misleading.
I hope that someone else can save a some time reading this.
Andere Tipps
You don't have to activate the "Publishing Infrastructure" feature.
Actually, when you activate the "Publishing Infrastructure" feature, it activates a bunch of other feature. I've tracked the one that needs to be activated in order not to have the UnauthorizedAccessException and it is the "Enterprise Wiki Layouts" feature. I took a look at the code behind the feature activated and found that it create a TaxonomyField (WikiPageCategories).
What I found out, is that all you needed, is to have to following code in a Site scope feature:
TaxonomySession taxonomySession = new TaxonomySession(site.RootWeb, false); <-- Important to call with RootWeb
Group siteCollectionGroup = taxonomySession.DefaultSiteCollectionTermStore.GetSiteCollectionGroup(site);
Then, you can call the GetSiteCollectionGroup within any Web Feature without it causing the UnauthorizedAccessException.