C# ASP.NET 成员资格:如何将用户设置为已登录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/912276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:39:09  来源:igfitidea点击:

ASP.NET Membership: how to set the user as logged in

c#asp.netasp.net-membershipmembership

提问by marcgg

I am trying to get the Membership Provider to work.

我正在尝试让会员提供程序工作。

So far I have:

到目前为止,我有:

 <asp:Login ID="Login1" runat="server" OnAuthenticate="Login1_Authenticate">
 </asp:Login>

calling :

打电话:

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    if(Membership.ValidateUser(Login1.UserName, Login1.Password))
    {
        Response.Redirect("/admin/default.aspx");
        // Set the user as logged in?
    }
}

If I enter the correct login/password, the ValidateUser function returns true. So my question is: how do I set the user as logged in?

如果我输入正确的登录名/密码,则 ValidateUser 函数返回 true。所以我的问题是:如何将用户设置为登录状态?

I am testing this in my pages doing :

我正在我的页面中测试这个:

protected void Page_Load(object sender, EventArgs e)
{
    if ( Membership.GetUser()==null)
    {
        Response.Redirect("/admin/login.aspx");
    }
    // else "you are logged in, congratulations"                
}

I would have used the default functions, but it is just not working and a google search made me think that I will save time by actually recoding all that myself.

我会使用默认功能,但它只是不起作用,谷歌搜索让我认为我可以通过自己重新编码来节省时间。

Anything will help!

任何事情都会有所帮助!

EDIT: Regarding the accepted answer, it is the correct one for "how to set the user as logged in" and works fine. It didn't fixed my specific problem but only a part of it. Thought if you look thought the comments you will find interesting pointers.

编辑:关于接受的答案,它是“如何将用户设置为登录”的正确答案,并且工作正常。它没有解决我的具体问题,而只是解决了其中的一部分。想如果你看一下评论你会发现有趣的指针。

EDIT 2 and solution: Ok I finally worked it out thanks to all the comments. Here is what I did, it's simpler than what I expected :

编辑 2 和解决方案:好的,感谢所有评论,我终于解决了。这是我所做的,它比我预期的要简单:

Page that checks login state:

检查登录状态的页面:

 protected void Page_Load(object sender, EventArgs e)
 {
     if ( !Request.IsAuthenticated)
     {
         Response.Redirect("/admin/login.aspx");
     }  

Log out:

登出:

   protected void LoginStatus1_Logout(object sender, LoginCancelEventArgs e)
   {
       FormsAuthentication.SignOut();
       Response.Redirect("/admin/login.aspx");
   }
}

web.config:

网络配置:

<authentication mode="Forms" />

login:

登录:

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    if(Membership.ValidateUser(Login1.UserName, Login1.Password))
    {
        FormsAuthentication.SetAuthCookie(Login1.UserName, true);
        Response.Redirect("/admin/default.aspx");

    }
}

采纳答案by Gromer

Put this in Login1_Authenticatebefore calling Response.Redirect("/admin/default.aspx");

Login1_Authenticate在打电话之前把这个放进去Response.Redirect("/admin/default.aspx");

FormsAuthentication.SetAuthCookie("username", true);

回答by dtc

Gromer has the answer, but you can also take a look at this MSDN article to learn more:

Gromer 有答案,但您也可以查看这篇 MSDN 文章以了解更多信息:

http://msdn.microsoft.com/en-us/library/ms998347.aspx

http://msdn.microsoft.com/en-us/library/ms998347.aspx

回答by Matthew Jones

Try moving your code and Gromer's suggestion to the LoggedIn event.

尝试将您的代码和 Gromer 的建议移至 LoggedIn 事件。

protected void Login1_LoggedIn(object sender, EventArgs e)
    {
        if(Membership.ValidateUser(Login1.UserName, Login1.Password))
        {
            FormsAuthentication.SetAuthCookie(Login1.UserName, true);
            Response.Redirect("/admin/default.aspx");
        }

    }

EDIT: Like Gromer said, only do this if you have to execute some business code after the user is logged in and before s/he is redirected.

编辑:就像 Gromer 说的那样,只有在用户登录后和他/她被重定向之前必须执行一些业务代码时才这样做。

EDIT EDIT: Visual Studio describes the Authenticate event as, "called to authenticate the user," which implies that the user is not authenticated before the event is called. Thus, you cannot confirm that the user is logged in because s/he has not been authenticated yet.

编辑 编辑:Visual Studio 将 Authenticate 事件描述为“调用以对用户进行身份验证”,这意味着在调用事件之前未对用户进行身份验证。因此,您无法确认用户是否已登录,因为他/她尚未通过身份验证。

回答by Jason

While I don't know how much help this will be, this is boilerplate code I use to discern between admin users or regular users. Works great for me.

虽然我不知道这会有多大帮助,但这是我用来区分管理员用户或普通用户的样板代码。对我很有用。

On your login page, probably onclick create your user object and call some function with this code (UserRole is an Enum with your roles):

在您的登录页面上,可能 onclick 创建您的用户对象并使用此代码调用一些函数(UserRole 是具有您角色的 Enum):

If admin Then 
            If role = UserRole.Admin Then
                RedirectFromLoginPage(username & "|" & userid, False)
                Return True
            Else
                Return False
            End If
        Else
            If String.IsNullOrEmpty(Current.Request.QueryString("ReturnUrl")) Then
                SetAuthCookie(username & "|" & userid, True)
            Else
                RedirectFromLoginPage(username & "|" & userid, True)
            End If
            Return True
        End If

In your web.config:

在您的 web.config 中:

<location path="admin">
    <system.web>
        <authorization>
            <allow roles="Admin"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</location>
.....
<system.web>
<authentication mode="Forms">
        <forms loginUrl="/registration/login.aspx" timeout="129600"/>
    </authentication>
    <authorization>
        <allow users="*"/>
    </authorization>
</system.web>

... and if you really want, in your Global.asax page:

...如果你真的想要,在你的 Global.asax 页面:

    Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
    If Request.IsAuthenticated Then
''
'get your roles for the current user'
''
 Dim userRoles() As String = Split(roles, "|")
        'Add the roles to the User Principal'
        HttpContext.Current.User = New GenericPrincipal(User.Identity, userRoles)
    End If
End Sub