Search code examples
.netsharepointweb-parts

Sharepoint OpenWeb() returning null when not logged in


I have a SP webpart that pulls data from a datatable and displays formatted. Most of the instances of this web part work fine, but this specific one returns null when it is called. However, if I am logged into the site (and not anon) the webpart returns the list. So odd. I checked all the involved web objects and they all inherit from parent, which does not require a login to view.

Here is a code snippet: (Keep in mind I inherited this code and it is by no means 'good')

public static DataTable GetDataTableFromSPList(string webUrl, string listName, Int32 numToReturn, string sortCol, string  ascend)
{
            SPListItemCollection coll = null;
            DataTable dt = null;

                string siteUrl = GetUrlPrefix();
                using (SPSite site = new SPSite(siteUrl + webUrl))
                {
                    using (SPWeb web = site.OpenWeb())  //this returns NULL when logged in anon???
                    {
                        try
                        {
                            SPList list = null;
                            list = web.Lists[listName];

                            SPQuery query = new SPQuery();
                            string qry = "<OrderBy><FieldRef Name='" + sortCol + "' Ascending='" + ascend.ToUpper() + "' /></OrderBy>";

                            query.Query = qry;
                            query.RowLimit = Convert.ToUInt32(numToReturn);
                            coll = list.GetItems(query);

                            if (coll != null)
                            {
                                dt = coll.GetDataTable();
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteLog(ex.Message, System.Diagnostics.EventLogEntryType.Error);
                        }
                    }
                }

            return dt;
}

Solution

  • I've never experienced this issue either, but after reading a couple of articles about it, it seems that this is the "default behavior".

    The OpenWeb() method returns the "lowest" web it can find, for example:

    and your code is like this:

    var web = site.OpenWeb("subsite/subsite1");
    

    the web object will be representing "subsite" and not "subsite1" because "subsite1" does not exist.

    In your case, it is definitely a permission issue. Is anonymous access enabled for the whole site-collection, or to be specific, is it enabled for the web you are trying to call with your code? If so, can users (anonymously) open the web?

    The easiest way to fix it, is to wrap the method with SPSecurity.RunWithElevatedPrivileges, however it's not very elegant.

    OpenWeb() Reference

    SPSecurity.RunWithElevatedPrivileges Reference