HttpContext.Current.User.Identity.Name如何知道存在哪些用户名?

问题描述 投票:33回答:5

这不一定是一个问题,我只是好奇它是如何工作的。我有一个方法:

public static bool UserIsAuthenticated()
{
    bool isAuthed = false;
    try
    {
        if (HttpContext.Current.User.Identity.Name != null)
        {
            if (HttpContext.Current.User.Identity.Name.Length != 0)
            {
                FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                FormsAuthenticationTicket ticket = id.Ticket;
                isAuthed = true;
                string MyUserData = ticket.UserData;
            }
        }
    }
    catch { } // not authed
    return isAuthed;
}

如果用户不存在,HttpContext.Current.User.Identity.Name将返回null,但它如何知道哪些用户名存在或不存在?

c# asp.net httpcontext
5个回答
24
投票

HttpContext.Current.User.Identity.Name返回null

这取决于您的web.config文件中的身份验证模式是设置为Forms还是Windows。

例如,如果我像这样编写身份验证:

<authentication mode="Forms"/>

然后因为身份验证模式=“表单”,我将为用户名获取null。但是,如果我将身份验证模式更改为Windows,如下所示:

<authentication mode="Windows"/>

我可以再次运行应用程序并检查用户名,我将成功获取用户名。

有关更多信息,请参阅System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET


53
投票

用于Windows身份验证

选择你的项目。

按F4

禁用“匿名身份验证”并启用“Windows身份验证”


3
投票

假设“用户”(也就是您)必须登录的网络环境。通常这是用户ID(UID)和密码(PW)。那么,你的身份是什么,或者你是谁?您是UID,这可以从您的登录会话中“命名”。简单!它也应该在需要您登录的互联网应用程序中工作,例如Best Buy和其他人。

当我打开我需要使用的Web应用程序的默认页面时,这将从我的会话中提取我的UID或“名称”。现在,在我的实例中,我是域的一部分,所以我可以使用初始Windows身份验证,它需要验证我是谁,因此代码的第二部分。至于表单身份验证,它将依赖于发送到您的工作站/计算机的票证(最有可能是cookie)。代码看起来像:

string id = HttpContext.Current.User.Identity.Name;

// Strip the domain off of the result
id = id.Substring(id.LastIndexOf(@"\", StringComparison.InvariantCulture) + 1);

现在它有我的公司名称(又名UID),可以在屏幕上显示。


2
投票

还检查一下

<modules>
      <remove name="FormsAuthentication"/>
</modules>

如果你发现这样的东西,只需删除:

<remove name="FormsAuthentication"/>

来自web.config并在这里你去它将工作正常我已经测试过它。


1
投票

[HttpContext.Current.User]如何知道哪些用户名存在或不存在?

让我们看一下这种方法的一个例子。假设您正在使用表单身份验证并触发“OnAuthenticate”事件。此事件发生在“when the application authenticates the current request”(Reference Source)。

到目前为止,应用程序根本不知道你是谁。

由于您使用的是表单身份验证,因此首先通过调用.ASPAUTH来解析身份验证cookie(通常是ExtractTicketFromCookie)。这称为FormsAuthentication.Decrypt(此方法是公开的;您可以自己调用它!)。接下来,它调用Context.SetPrincipalNoDemand,将cookie转换为用户并将其填充到Context.UserReference Source)。

© www.soinside.com 2019 - 2024. All rights reserved.