0

I have an Application Page (.aspx) in which I get data from a List.
I am fetching data from this List quite often in different scenarios.

I have made a property in the code behind which gets me the SPList when ever I call it:

SPList _listCategory;

public SPList CategoryList
{
    get
    {
        if (_listCategory == null)
            _listCategory = SPContext.Current.Site.RootWeb.Lists["Category"];

        return _listCategory;
    }
}

My client recently asked me to change it so only Users with Full Control can access this List (the page is accessible for everybody else), which means I have to wrap a SPSecurity.RunWithElevatedPrivileges around some code blocks - I just don't know which.

Should I wrap it around my Property, like so:

public SPList CategoryList
{
    get
    {
        if (_listCategory == null) 
        {
            SPSecurity.RunWithElevatedPrivileges(() => 
            {
                using (var site = new SPSite(SPContext.Current.Site.ID))
                {
                    _listCategory = site.RootWeb.Lists["Category"];
                }
            });
        }

        return _listCategory;
    }
}

Or wrap it around the code which calls the Property, like so:

public void SomeMethodThatDoesStuff()
{
    SPSecurity.RunWithElevatedPrivileges(() => 
    {
        var categoryItems = CategoryList.Items;
    });
}
1

Both the code has the same effect. Much cleaner version is to use it inside the Property.

Note - Its is preferred to use UserToken instead of elevating code. You can read more Best way to Impersonate in SharePoint

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy