HttpContext.Current.User.Identity.Name永远的String.Empty [英] HttpContext.Current.User.Identity.Name is always string.Empty

查看:240
本文介绍了HttpContext.Current.User.Identity.Name永远的String.Empty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我使用一个自定义的MembershipProvider。

我想知道一个应用场景中当前用户名,但是当我试图访问HttpContext.Current.User.Identity.Name它总是返回的String.Empty。

 如果(Membership.ValidateUser(tbUsername.Text,tbPassword.Text))
{
    FormsAuthentication.SetAuthCookie(tbUsername.Text,真);
    布尔X = User.Identity.IsAuthenticated; //真正
    字符串Y = User.Identity.Name; //
    FormsAuthentication.RedirectFromLoginPage(tbUsername.Text,cbRememberMe.Checked);
}

我缺少的东西吗?


解决方案

  FormsAuthentication.SetAuthCookie(tbUsername.Text,真);
布尔X = User.Identity.IsAuthenticated; //真正
字符串Y = User.Identity.Name; //

你的问题是在这一点上,你只设置身份验证Cookie,这被窗体身份验证模块内创建将不会发生,直到有新的请求的IPrincipal - 所以在这一点上HttpContext.User中是一个奇怪的状态。一旦发生重定向的话,因为它是从浏览器一个新的请求到达您的页面之前cookie将获得阅读和创建正确的用户对象。

饼干的请求完成后,仅在浏览器上设置

顺便说一句RedirectFromLoginPage创建窗体身份验证cookie的,无论如何,你不必做手工

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.Name it always returns string.Empty.

if (Membership.ValidateUser(tbUsername.Text, tbPassword.Text))
{
    FormsAuthentication.SetAuthCookie(tbUsername.Text, true);
    bool x = User.Identity.IsAuthenticated; //true
    string y = User.Identity.Name; //""
    FormsAuthentication.RedirectFromLoginPage(tbUsername.Text, cbRememberMe.Checked);
}

Am I missing something?

解决方案

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

这篇关于HttpContext.Current.User.Identity.Name永远的String.Empty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆