HttpContext.Current.User.Identity.Name is always string.Empty

后端 未结 7 805
清歌不尽
清歌不尽 2020-12-01 05:21

Hi I use a custom MembershipProvider.

I want to know the current username during an application scenario, but when I try accessing HttpContext.Current.User.Identity.

相关标签:
7条回答
  • 2020-12-01 05:57

    Please try System.Web.HttpContext.Current.Request.LogonUserIdentity.Name instead of User.Identity.Name. It worked for me.

    0 讨论(0)
  • 2020-12-01 05:58

    in VS Community 2015 version, if you create a web forms application, it automatically add codes in web.config node to remove FormsAuthentication, try remove below section

    <modules>
      <remove name="FormsAuthentication"/>
    </modules>
    
    0 讨论(0)
  • 2020-12-01 05:59

    If you're looking for the name of the user from the membership provider, try something like this ...

    var user = Membership.GetUser( HttpContext.Current.User.Identity.Name );
    
    0 讨论(0)
  • 2020-12-01 06:09
    FormsAuthentication.SetAuthCookie(tbUsername.Text, true);
    bool x = User.Identity.IsAuthenticated; //true
    string y = User.Identity.Name; //""
    

    The problem you have is at this point you're only setting the authentication cookie, the IPrincipal that gets created inside the forms authentication module will not happen until there is a new request - so at that point the HttpContext.User is in a weird state. Once the redirect happens then, because it's a new request from the browser the cookie will get read before your page is reached and the correct user object created.

    Cookies are only set on the browser after a request is completed.

    As an aside RedirectFromLoginPage creates a forms auth cookie anyway, you don't need to do it manually

    0 讨论(0)
  • 2020-12-01 06:11

    As already suggested FormsAuthentication.RedirectFromLoginPage() method, sets the Authentication Cookie automatically.

    However in my case, i had nested web applications where i had cleared <httpModules> tag in child application (so that it does not inherit httpModules from its parent application) in the web.config file. Removing the unwanted parent httpModules made everything work again.

    its better to check this tag before complicating things :)

    0 讨论(0)
  • 2020-12-01 06:15

    The value of HttpContext.Current.User.Identity.Name is set by the call to RedirectFromLoginPage. You can get the current user id from HttpContext.Current.User.Identity.Name once you are redirected to a new page. I'm not sure why you would need to access the user name through the User property in this context, couldn't you just use the value contained in tbUsername.Text?

    0 讨论(0)
提交回复
热议问题