.net Core实现登录界面(Session,Cookies)

Login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="WebApplication2.Login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Login.aspx</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            username:&nbsp; <asp:TextBox ID="username" runat="server"></asp:TextBox>
            <br />
            passwd:&nbsp;&nbsp; <asp:TextBox ID="userpasswd" runat="server" ></asp:TextBox>
            <br />
            <asp:CheckBox ID="cb1" runat="server"  Text="Rember me"/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <%--<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
                <asp:ListItem Value="1">male</asp:ListItem>
                <asp:ListItem Value="female">2</asp:ListItem>
            </asp:DropDownList>--%>
            <br />
            <asp:Button ID="btlogin" runat="server" Text="login" OnClick="btlogin_Click" />
        </div>
    </form>
</body>
</html>

Login.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace WebApplication2
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            //若存在Session(会话未消失)
            if (Session["username"] != null && Session["userpwd"] != null)
            {
                Response.Redirect("Index.aspx");
            }
            else if(Request.Cookies["Name"] != null && Request.Cookies["Passwd"] != null)
            {
                Session["username"] = Request.Cookies["Name"].Value;
                Session["userpwd"] = Request.Cookies["Passwd"].Value;
                Response.Redirect("Index.aspx");
            }
            else
            {
                Response.Write("You haven't logged in to this website or (The Session or The Cookies has expired.)");
            }
            //Response.Write("ipb" + IsPostBack);
            if (!IsPostBack)
            {
                Session["rember"] = false;
            }

            

        }

        protected void btlogin_Click(object sender, EventArgs e)
        {
            
            if (username.Text != null && userpasswd != null)
            {
                string name = username.Text;
                string passwd = userpasswd.Text;
                bool CanLogin = false;
                {
                    string strConn = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
                    SqlConnection conn = new SqlConnection(strConn);
                    conn.Open();

                    try
                    {
                        SqlCommand cmd = new SqlCommand();
                        cmd.Connection = conn;
                        cmd.CommandText = "select count(*) from T_USER where UName = '" + name + "'";
                        cmd.CommandType = CommandType.Text;
                        if (Convert.ToInt32(cmd.ExecuteScalar()) == 0)
                        {
                            ClientScript.RegisterStartupScript(
                            this.GetType(),
                            "Alert",
                            "<script> alert(\"用户名不存在\")</script >"
                            );

                        }
                        else {
                            cmd.CommandText = "select count(*) from T_USER where UName = '" + name + "' and " + " UPwd = '" + passwd + "'";
                            cmd.CommandType = CommandType.Text;

                            //ExecuteScalar只返回第一行第一列的数据
                            //适合用来处理标量结果(有或无)
                            int result = Convert.ToInt32(cmd.ExecuteScalar());
                            if (result == 0)
                            {
                                ClientScript.RegisterStartupScript(
                                    this.GetType(),
                                    "Alert",
                                    "<script> alert(\" 用户名或密码不正确\")</script >"
                                    );
                            }
                            else
                            {
                                CanLogin = true;
                            }
                        }
                        
                    }
                    catch(SqlException ex)
                    {
                        Response.Write(ex.Message);
                    }
                    finally
                    {
                        conn.Close();
                    }

                }
                
                //if (username.Text.Equals("admin") && userpasswd.Text.Equals("123"))
                

                if (CanLogin == true)
                {
                    Session["username"] = name;
                    Session["userpwd"] = passwd;
                    if (cb1.Checked)
                    {
                        int Days = 7;
                        Response.Cookies["Name"].Value = username.Text;
                        Response.Cookies["Passwd"].Value = userpasswd.Text;
                        Response.Cookies["Name"].Expires = DateTime.Now.AddDays(Days);
                        Response.Cookies["Passwd"].Expires = DateTime.Now.AddDays(Days);
                    }
                    
                    Response.Redirect("Index.aspx");
                }
                else
                {
                    Response.Write("用户名或密码输入不正确!");
                }
            }
            else
            {
                Response.Write("用户名或密码输入不完全!");
            }

        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}

Index.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="WebApplication2.Index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Index</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h1>这是index页面!</h1>
            <br />
            <p>
                username: <% if(Session["username"] != null)
                                  Response.Write(Session["username"].ToString()); 
                             %>
                <br />
                userpasswd: <% if(Session["userpwd"] != null)
                                    Response.Write(Session["userpwd"].ToString()); 
                               %>
            </p>
        </div>
        <asp:Button ID="btExit" runat="server" Text="Exit" OnClick="btExit_Click" />
    </form>
</body>
</html>

Index.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            bool Logged = false;
            if (Session["username"] != null && Session["userpwd"] != null)
            {
                Response.Write("Session Exist."+"<br />");
                Logged = true;
            }
            if (Request.Cookies["Name"] != null && Request.Cookies["Passwd"] != null)
            {
                Response.Write("Cookies Exist." + "<br />");
                Session["username"] = Request.Cookies["Name"].Value;
                Session["userpwd"] = Request.Cookies["Passwd"].Value;
                Logged = true;
            }
            if(Logged == false)
            {
                Response.Write("<script>alert("+"\"请先登录用户\""+");</script>");
                Response.Redirect("Login.aspx");
            }
        }

        protected void btExit_Click(object sender, EventArgs e)
        {
            Session.Remove("username");
            Session.Remove("userpwd");
            //Session.Clear();
            Response.Cookies["Name"].Expires = DateTime.Now.AddDays(-1);
            Response.Cookies["Passwd"].Expires = DateTime.Now.AddDays(-1);

            Response.Redirect("Login.aspx");
        }
    }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是ASP.NET Core MVC的登录代码实现: 1. 在Startup.cs中添加身份验证和授权服务: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Account/Login"; options.AccessDeniedPath = "/Account/AccessDenied"; }); services.AddAuthorization(options => { options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin")); }); // ... } ``` 2. 在AccountController.cs中添加登录和注销动作: ```csharp public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager) { _userManager = userManager; _signInManager = signInManager; } [HttpGet] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { return RedirectToLocal(returnUrl); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Logout() { await _signInManager.SignOutAsync(); return RedirectToAction(nameof(HomeController.Index), "Home"); } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction(nameof(HomeController.Index), "Home"); } } } ``` 3. 在视图中添加登录表单: ```html @model LoginViewModel <form asp-controller="Account" asp-action="Login" asp-route-returnUrl="@ViewData["ReturnUrl"]" method="post" class="form-horizontal" role="form"> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group"> <label asp-for="Email" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Email" class="form-control" /> <span asp-validation-for="Email" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="Password" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Password" class="form-control" /> <span asp-validation-for="Password" class="text-danger"></span> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <div class="checkbox"> <label> <input asp-for="RememberMe" /> @Html.DisplayNameFor(m => m.RememberMe) </label> </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-default">Log in</button> </div> </div> </form> ``` 这些代码将创建一个基本的登录和注销功能,用于保护应用程序中的受保护资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值