Search code examples
c#.netwcfasp.net-4.5

setting HttpContext.Current.User throws null reference exception


This is a WCF Oneway operation. HttpContext.Current.User is cleared in those operations, that is the reason I added a behavior that saves the User before it is cleared. Later I want to re-set the HttpContext.Current.User with the value I saved but I'm getting an exception:

HttpContext.Current.User = (RolePrincipal)userThatWasSavedBefore;

Object reference not set to an instance of an object.
at System.Web.HttpContext.SetPrincipalNoDemand(IPrincipal principal, Boolean needToSetNativePrincipal)
at System.Web.HttpContext.set_User(IPrincipal value)
at (My Function)

Why can't I set the user? What is the problem?


Solution

  • The reason you can't set it is most likely that the request has finished. Setting the User property results in ASP.NET trying to call back into per-request data structures, and if these data structures have been released then the resulting behavior is undefined.

    For one-way operations, WCF invokes application code while simultaneously telling ASP.NET not to wait for the application code to finish and to just complete the request immediately. For this reason is it strongly recommended that you don't access HttpContext from a one-way operation.