Home » .Net Framework

httpcontext.current.user.identity.isauthenticated always false


please help me, I create two pages, the first one is the login page with user name and password textboxes - (not asp login control) , when clicking login button I check the login authentication, if it is true redirect to default page. in the default page if !IsCallBack then i check httpcontext.current.user.identity.isauthenticated

if it is false i redirect the user to the login page. but my problem is that the httpcontext.current.user.identity.isauthenticated is always false.

Below the section of authentication in web config



authenticationmode="Forms">formsloginUrl ="FrmUserLogin.aspx"


protection ="All"


timeout ="1"


name ="LoginRedirectCallback"


path ="/LoginRedirectCallback"


requireSSL ="false"


slidingExpiration ="true"


defaultUrl ="FrmDBLoginConfigaspx.aspx"


cookieless ="UseDeviceProfile"








enableCrossAppRedirects ="false">credentialspasswordFormat="Clear">username ="admin"password ="admin"/>credentials>forms>authentication>

thank you for any help.


Best Regards,


5 Answers Found


Answer 2

Are you using FormsAuthentication.Authenticate method? 


Answer 3

Thank you for your help. yes I use  FormsAuthentication.Authenticate, do you have any suggestions?


Answer 4


You will have to use FormsAuthentication.SetAuthCookie() method with Authenticate method

check this sample: http://www.codeproject.com/KB/aspnet/custom_authentication.aspx



Answer 5

Thank you sanjibsinha.

 Your link was very useful for me. again thank you for your help. 



Hi People,

I have a Req where am fetching the currently logged in windows user from my SL app.

I have writen a seperate method in WCf Service which returns the Currently logged on user using

the code user_names = System.Web.HttpContext.Current.User.Identity.Name;

However I find  that these code works while debugging My Silverlight Application.

But it is not Working when i pulblish My SL APP and WCF Code into different domains in IIS.

A)WCF-Anonymous authentication is enabled

B)SL-Anonymous Authentication is enabled.

If at all i uncheck the Anonymous Authentication in WCF It gives me Some Cross domain issue.

I have integrated the Clientaccesspolicy,crossdomain files in my Root Folder.

Is there anything do i need to configure or change.

Plz Help






I'm writing an application where I need to grab the Windows user ID. 

Using HttpContext.Current.User.Identity.Name works, but it only works locally.  When I run the application on the server, (from my machine, pointing to the server URL) the HttpContext.Current.User.Identity.Name is null.

Does anyone have any suggestions how to solve this?



I'm fairly new to WIF so I'm working through the samples and WIF training kit.  The training kit solutions are working great and while I was working through the silverlight example I thought I'd try a from scratch version, not using the solutions provided by the training.  My version of the sample code differs in service/method names and the silverlight template, I used a SL 4 navigation application instead of a basic app.  Also, I should point out that in my simple STS I have code that reads then login name and if it contains the word admin it adds the "admin" role claim else it adds a "user" role claim.  When I debug-run the solution, it walks through the sts login process and into the sl application just fine.  I can see and use the Identity object and the new claims in the client side and can react accordingly in the UI.  The problem happens when I make a service call, which is a simple method that returns a string.  I get the ever-helpful NotFound exception.  What I found so far was that the ClaimsAuthorizationManager.CheckAccess is never called.  However, if I add a <location> set in the web.config allowing access for everybody (ie user=*) then the authorization manager check acess fires but the httpcontext.current.user.identity is null.  I don't think I should have to use the location settings in the web.config because the training kit doesn't...so is this an IIS 7 application/file setting.  I've win-diffed the heck out of the config files and some of the code and I can't seem to get a round the NotFound.  

Anybody run into this type of behavior and willing to help a n00b out?



I am using Forms  Authentication.

I set the cookie when user logs in.

Welcome text =  HttpContext.Current.User.Identity.Name

Logout = Session.Abandon and Session.Clear()

Now when I logon using different user name i still see my previous login name when I do"




We've  been trying to fix this one for a couple years, and I'm just out of ideas, so any help is really appreciated!

We've got a fairly large, complex web application that uses Forms Authentication to authenticate users.  Throughout the application we store and retrieve information about users in the Session object, and in some cases in cookies.  In a couple places we check for the existence of the context, and if it's null we send the user back to the login page to re-establish the session. 

Just a quick run-down of this web app: C#, .NET 3.5, IIS 6, ASP.NET State Service to manage session

As for the session timer, we use our own home-grown timer, which is basically a client-side timer, which is backed up by a check to the SQL database to see when their last activity was.  This seems to work well for us.  It's not perfect, but it allows us to notify the user before the session times out, and allows us to be certain we're not logging a user out before their 60 minutes of inactivity is up.

What's happening is that certain users are being logged out after just a few minutes.  We've eliminated the timer as a cause and believe what's happening is the HttpContext.Current is null, so the user is logged out.  We do not know why the HttpContext.Current is null, and I understand there are many reasons that may occur. 

What I'm trying to figure out is, is there any way to re-establish the context once it is null?  If not, is there anything I can do at this point other than have the user login again?  We're also trying to figure out a better way of managing user information (preferences, roles, flags, history, etc), but everything needs context to use, right?  Cookies, sessions, cache, etc. all require a response or request, correct? 

I hope this makes sense, because I really need help with this.  I've searched the forums here, and found many posts about HttpContext.Current going null, but not a lot of solutions for this...

Thanks for your help!




I have used IIdentity WinId = HttpContext.Current.User.Identity; to get user information for the logged in user, but out of 5 user one user is getting other user's details. please suggest me how to sort out this issue.

I am not storing this details nor i processed before displaying it, i simply get value through above line and displaying it in the message box. So no question of overwriting by cookies or any other processes.




The crux of my problem is that I want to impersonate  a user’s NTLM credentials in the context of a SharePoint custom security trimmer to execute HttpWebRequests to check user access to URLs. 

When accessing WindowsIdentity.GetCurent() in the security trimmer, the System.Security.Principal.WindowsIdentity object returns the identity of the application pool running the search query service, NOT the currently logged in user.  

When accessing System.Threading.Thread.CurrentPrinciple.Identity in the security trimmer, the Microsoft.IdentityModel.Claims.ClaimsIdentity object of the current logged in user is returned.  However, there is a catch.



If I execute the following code in a .NET web application, the cast of the ClaimsIdentity to a WindowsIdentity succeeds because the identity has the authentication type of NTLM. 


WindowsIdentity winId = (WindowsIdentity)System.Threading.Thread.CurrentPrincipal.Identity;
WindowsImpersonationContext wic = winId.Impersonate();
request.Credentials = CredentialCache.DefaultCredentials;

//access means a response comes back when a request is made to the urlusing (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
 returnStatus = true;

However, when I execute the same code in the context of the SharePoint security trimmer (the search query service lives in its own IIS worker process of w3wp.exe), I get an invalid cast exception.  The reason for this is because the authentication type is federation (even though SharePoint is setup using windows authentication, the search service application proxy is passed a security token from the security token service).  

If I take a step back, some may ask why I don’t do something like this in the security trimmer:


//user in format <ppl>\<username>string[] credentials = user.Split(newstring[] { "\\" }, StringSplitOptions.None);
WindowsIdentity impersonatedIdentity = new WindowsIdentity(string.Format("{0}@{1}", credentials[1], credentials[0]));
wic = impersonatedIdentity.Impersonate();

When this code executes, the WindowsIdentity is property returned.  However, the authentication type is Kerberos and although impersonation does not fail, a request made that should succeed actually fails.

Is anyone familiar with a way of using the claims identity to do impersonation? Is it even possible to achieve what I want to do in the given context?  Any other suggestions? 

I appreciate any information.





I am getting null reference for System.Web.HttpContext.Current.Cache;

I am trying to tun Vs 2008 unit test ...and it is using default hosting.

Is there any way we can run on asp.net host ?

anyone knows good link ?

I have an intermittent issue where HttpContext.Current is null.  I do have aspNetCompatibilityEnabled="True".  I can duplicate it by restarting the webservice and make the request.  The first request has the HttpContext.Current set to null but subsequent requests have the proper HttpContext.  I've done some tracing and the messages are exactly the same.

What else is weird is that the HttpContext is NOT null in my global.asax but by the time it hits my custom UsernamePasswordValidator, it is set to null.


Any ideas on what i'm doing wrong?

HttpRequest from tracing:

<HttpRequest><Method>POST</Method><QueryString></QueryString><WebHeaders><Cache-Control>no-cache</Cache-Control><Connection>Keep-Alive</Connection><Content-Length>799</Content-Length><Content-Type>text/xml; charset=utf-8</Content-Type><Accept>*/*</Accept><Accept-Encoding>identity</Accept-Encoding><Host>mydomain.com</Host><User-Agent>Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E; InfoPath.2)</User-Agent><SOAPAction>"http://tempuri.org/ICategoryService/GetAvailablePickList"</SOAPAction></WebHeaders></HttpRequest><:Envelopexmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><:Header><Securitys:mustUnderstand="1"xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><u:Timestampu:Id="6a7e13c0-8dc9-431a-87d4-11599ef73889"><u:Created>2010-09-02T15:30:40.039Z</u:Created><u:Expires>2010-09-02T15:35:40.039Z</u:Expires></u:Timestamp><UsernameTokenu:Id="95c14471-08c9-47d1-beae-5367ca4d53e8"><Username><!-- Removed--></Username><Password><!-- Removed--></Password></UsernameToken></Security><Tos:mustUnderstand="1"xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">https://sef-carteada-vm.roomstogo.rtg/CategoryMaintenance/Services/CategoryService.svc</To><Actions:mustUnderstand="1"xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/ICategoryService/GetAvailablePickList</Action></:Header><:Body><GetAvailablePickListxmlns="http://tempuri.org/"></GetAvailablePickList></:Body></:Envelope>



I have noticed a strange behaviour in my ASP.net 2.0 application.

 I have some logic in my aspx page that accesses some Session variables fine, then accesses some app_code and most of the time the HTTPContext.Current.Session returns the variable back fine.  However, I have noticed that sometimes this Session returns null, like it has lost it's "pointer" to the current HTTPContext.

 Is this a known bug, has anyone seen something like this before?

  Any help would be appreciated, thanks,





Hello, everyone!

Well, I made some researches to discover how can I use session variables in App_code. A lot of sites show me answer is use HttpContext.Current.Session. But I´m having following error: The name 'HttpContext' does not exist in the current context.

What can I do?


For some strange reason HTTPContext.Current.Session is null in SharePoint 2007 web application.

Session is enabled everywhere and used to work so its not a setup issue. Something got corrupted at some point either via patches or something...

Doing "Reset To Definition" fixes the issue, but I can't do that in production environment and what is reset to definition has to do with session being null?

Searching on the web found a post from someone having same exact issue:


I need to know how to FIX this w/o doing complete "Reset To Definition".


In place of a Response.End, I want to issue a HttpContext.Current.ApplicationInstance.CompleteRequest(),

since this is supposed to help avoid the Thread Abort error.  But I am unclear how to do this in a class module since 

there is no access to HttpContext apparently.  Does anyone know how to execute a CompleteRequest() in a class module?



Hi there,

If I use the following code

If File.Exists(HttpContext.Current.Server.MapPath(xmlDatasource)) Then

in my server control RenderContents handler I am getting the following error

"Error Rendering Control - An unhandled exception has occurred. Object reference not set to an instance of an object."

while in Design mode.

when I remove the  HttpContext.Current.Server.MapPath  from code, like this -

If File.Exists(xmlDatasource) Then

I get no error.


How can I get the server mapping for a file without using HttpContext.Current.Server.MapPath ?


I'm probably doing something wrong, but the error I am getting is: Microsoft.Moles.Framework.Behaviors.BehaviorMissingValueException: a value for Request.Url is missing

Here's my code:

privatevoid MockHttp()


   // Mock the HttpContext.Current

   System.Web.Moles.MHttpContext.CurrentGet = delegate()


    var req = new System.Web.Behaviors.BHttpContext();

    req.InstanceBehavior = null;


    return req;



   System.Web.Moles.MHttpRequest.AllInstances.UrlInternalGet = delegate(HttpRequest request)




   System.Web.Moles.MHttpRequest.AllInstances.UrlGet = delegate(HttpRequest request)


    returnnew System.Uri("http://localhost:80/unit-test");



  [TestMethod(), HostType("Moles")]

  publicvoid GetBaseUrlTest()



   string expected = string.Empty; 

   string actual;

   actual = MagicStrings.GetBaseUrl();

   bool IsNull = string.IsNullOrEmpty(actual);

   Assert.AreEqual<bool>(false, IsNull);



    public static string GetBaseUrl()
      System.Web.HttpContext context = System.Web.HttpContext.Current;
      if (context != null)
        string u = context.Request.Url.Host + ":" + context.Request.Url.Port.ToString();
        return String.Format(@"http://{0}", u);
      return MagicStrings.BaseProductionUrl;


Anyone know of a way (and how) I can intercept calls to the httpcontext.current.cache methods so that I can do some extra processing?

For example, when someone calls:

httpContext.Current.Cache.Add("some key", objSomeObject, Nothing, System.DateTime.Now.AddMinutes(63), Cache.NoSlidingExpiration, Caching.CacheItemPriority.NotRemovable, Nothing)
I want to be able to Intercept that call and find out:
1. What the "some key" value was AND
2. What the expiration value was.
All without having to filter through tons of code and change the calls.
PLUS, I don't want to have to rely on various developers compliance with inserting a call to
the tracking routine: if they use Cache.Add, my code gets called and I know what was passed.


I was under the impression that you could use the HttpContext.Current.Items collection to pass information between pages but it doesnt seem to work...

Lets say i have a Page1 ButtonClick, the button click handler stores a value in the collection like so; HttpContext.Current.Items("Test1") = "Test"

Then i do Response.Redirect("Page2.aspx").

In the Form_Load of Page2, HttpContext.Current.Items("Test1") contains nothing. Why does this not work when its all part of the same postback?

This would be perfect, because i wouldnt need to worry about clearing the values between requests because they would automatically get cleared each time the page was posted back.

So I've got this Class Library I built, and I use this:

HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"].ToLower() to get the application path/working directory when the DLL is consumed/excecuted by a client project. It works great. The problem is when I deploy the Class/DLL as a WCF service, this line of code generates the error "Object not set to an instance of an object".

 any ideas how to fix this? or an alternative to this? I need to get the path/folder of the application.


OS: win7 Home Premium  64bit,  iis7

Intelligencia.UrlRewriter v2.0.0.6

I find HttpContext.Current.Session always is null, but the website can run on win2003+iis6 and asp.net development server success.


I using static class to access HttpContext.Current.Session

    public static class xxxxxx
        public static int UserID
                object oUserID = HttpContext.Current.Session["UserID"];
                if (oUserID == null)
                    return 0;
                return int.Parse(oUserID.ToString());
                HttpContext.Current.Session["UserID"] = value;


      <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />

   <remove name="ScriptModule" />
      <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule,Intelligencia.UrlRewriter" preCondition="" />

    <sessionState mode="StateServer" cookieless="false" timeout="120" stateConnectionString="tcpip=" sqlConnectionString="data source=;Trusted_Connection=yes" />

application pools set to integrated


           I am presently using Entity Data Model. I am trying to develop Unit Test Cases for Data Access Layer / Business Access Layer as well. 

I am able to save data in database using Entity data model.  I created unit test from Test Menu -> Unit Test -> Selected Unit Test Wizard.
When I am trying to write test cases for DAL/BAL methods with Visual Studio Unit Test, its throwing error while referring object 
HttpContext.Current (for getting the Context object). 


using BusinessEntities;
public int SaveobjDAC(string LoginId, string FirstName)
                MyEntities entities = MyEntities.Context;  
                                                                      //Getting Error Here, refer below code

                MyTable obj = new MyTable();

                    obj.LoginID = LoginId;
                    obj.FirstName = FirstName;
                    return entities.SaveChanges();

BusinessEntities layer:


 public static MyEntities Context
                string objectContextKey = HttpContext.Current.GetHashCode().ToString("x");
                if (!HttpContext.Current.Items.Contains(objectContextKey))
                    HttpContext.Current.Items.Add(objectContextKey, new MyEntities());
                return HttpContext.Current.Items[objectContextKey] as MyEntities;

error at:


objectContextKey = HttpContext.Current.GetHashCode().ToString("x");

Appreciate you in advance for your valuable suggestions. Thank you!!


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure