Asp.Net 之 使用Form认证实现用户登录 (LoginView的使用)

时间:2021-02-14 09:23:40

1. 创建一个WebSite,新建一个页面命名为SignIn.aspx,然后在页面中添加如下的代码

            <div class="div_logView">
<asp:LoginView ID="loginView" runat="server" EnableViewState="false">
<AnonymousTemplate>
<div style="margin:14px auto; width:118px; float: left; height:36px;">
<a href="../WebPage/Register.aspx"><img src="../images/index/zc.png" alt="注册" /></a>
</div>
<div style="margin:14px auto; margin-left:15px; width:83px; float: left; height:36px;">
<a href="../WebPage/Login.aspx"><img src="../images/index/dl.png" alt="登录" /></a>
</div>
</AnonymousTemplate>
<LoggedInTemplate>
欢迎您!
[<asp:HyperLink ID="hlMemCenter" NavigateUrl="../MemberCenter/MemCenIndex.aspx" Text="会员中心"
runat="server" ForeColor="White" />]
[<asp:LinkButton ID="lbtCancel" OnClick="Cancle_Click" ForeColor="White" runat="server" >退出</asp:LinkButton>]
</LoggedInTemplate>
</asp:LoginView>
</div>

在LoginView控件里面 AnonymousTemplate 是用户没登录时候显示的内容, LoggedInTemplate 是用户登录后显示的内容,还有一个 RoleGroups 是控制角色相关的,这里就没了,因为不用。

2、运行起来,AnonymousTemplate内容没有显示出来,因为Form认证的设置还没实现

打开Web.config文件,然后找到<authentication mode="Windows" ></authentication>节点,修改为

<authentication mode="Forms" >
<forms defaultUrl="~/Default.aspx" name=".Auth" protection="All" loginUrl="~/Login.aspx" path="/"></forms>
</authentication>

3、登录时进行注册

//为用户添加身份验证
FormsAuthentication.SetAuthCookie(userName, true);

4、注销或退出是进行注销

//从浏览器删除身份验证
FormsAuthentication.SignOut();