Question

I have found that SPContext.Current.Web.CurrentUser is really unreliable. One out of ten requests that object comes back as null.

Is there an alternative to SPContext.Current.Web.CurrentUser?

Has anyone else seen this unreliability?

Is there a fix out there?

Was it helpful?

Solution

It would be cool if you posted the offending code and its surroundings, but some things to consider out of the top of my head:

  1. You might be getting the object too early in the lifecycle (say PreInit methods and such, or an HttpModule etc)
  2. You might be breaking the pipeline doing things like setting the HttpContext to null (I've seen that in SharePoint workarounds before)
  3. You might be behind a reverse proxy like Apache or Nginx making your KeepAlives go crazy, try testing the code outside your environment
  4. And some "is the green light one" for hardware issues, app pool reaching the maxium RAM or lack of it, SQL Server busy
  5. You may be using some PInvoke impersonation that makes the integrated authentication go bananas
  6. If you are using FBA the provider settings and the backend availability (AD, XML file, SQL Membership) might be failing -- but this is unlikely for it would be a different error.
  7. A messed around HttpModules section loves to break things too, have you tried in a new WebApplication with zero changes?
  8. I Like the number eight, so I thought I should give it eight vague ideas

TL;DR: Post your code :)

OTHER TIPS

I have only experienced this when I forget that I'm calling it out of context.

are you sure you are not trying to call this within SPSecurity.RunWithElevatedPrivileges() ?

plz try with this..

SPWeb spWeb = Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(System.Web.HttpContext.Current);
SPUser user = spWeb.CurrentUser;

or

using (SPSite spsite = new SPSite(url))
                {
                    using (SPWeb spweb = spsite.OpenWeb())
                    {
                       userObj = spweb.CurrentUser;
                    }
                }

plz also try with RunWithElevatedPreviliges()...

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top