我需要在成功登录后直接获取用户ID Guid.以下代码不起作用:

if (Membership.ValidateUser(txtUsername.Value, txtPassword.Value))
{
    FormsAuthentication.SignOut();
    FormsAuthentication.SetAuthCookie(txtUsername.Value, true);

    if (HttpContext.Current.User.Identity.IsAuthenticated)
    {
        // doesn't run
        Guid puk = (Guid)Membership.GetUser().ProviderUserKey;            
    }
}

以下代码可以正常工作:

if (Membership.ValidateUser(txtUsername.Value, txtPassword.Value))
{
    FormsAuthentication.SignOut();
    FormsAuthentication.SetAuthCookie(txtUsername.Value, true);

    MembershipUser user = Membership.GetUser(txtUsername.Value);

    if (user != null)
    {
        Guid puk = (Guid)user.ProviderUserKey;
    }
}

为什么会这样?除了SetAuthCookie美元,还有别的事要做吗?

推荐答案

因为当你拨打FormsAuthentication.SetAuthCookie(txtUsername.Value, true);时,你会将密钥存储在客户的cookies上.为此,您需要对用户进行响应.

简而言之,你的计划是这样的:

  1. 客户端发送他的用户名和密码.

  2. 服务器获取并判断它.如果它们有效,则服务器向客户端发送Set-Cookie报头.

  3. 客户机接收并存储它.对于每个请求,客户端都会将cookie发送回服务器.

更新@Jake

添加在HttpContext中设置User的示例

var identity = new System.Security.Principal.GenericIdentity(user.UserName);
var principal = new GenericPrincipal(identity, new string[0]);
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = principal;  

请注意,您可以创建从GenericPrincipalClaimsPrincipal继承的自定义主体类

Asp.net相关问答推荐

Thread.CurrentPrincipal 错误地声称是匿名的

我们可以在一个网页中使用多个表单吗?

无法为媒体类型application/x-www-form-urlencoded生成样本

Web 服务器配置为不列出此目录的内容. asp.net vs 2012 错误?

在 Sessions 中存储自定义对象

如何使用 SmtpClient.SendAsync 发送带有附件的邮箱?

如何在 C# 应用程序中调用 VBScript 文件?

如何在 ASP.Net 的客户端 (JavaScript) 上判断 Page.Validate()?

显示 ModalPopupExtender 时如何指定要运行的 javascript

这个rendersection的代码是什么意思?

使用 Ninject OWIN 中间件在 OWIN 启动中注入 UserStore

如何验证 WebClient 请求?

使用 VirtualPathProvider 从 DLL 加载 ASP.NET MVC 视图

头标记中的内联代码 - ASP.NET

ASP.Net 错误:应用程序池的标识无效

如何遍历自定义 vb.net 对象的每个属性?

主机与 DnsSafeHost

将对象传递给 HTML 属性

如何调试 w3wp clr.dll 错误

如何使用 int ID 列更改 ASP.net Identity 2.0 的表名?