首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET MVC AJAX 表單提交實戰:登入驗證與 Session 管理完整範例

     編輯:ASP.NET 基礎

完整頁面碼

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<html>
<head>
    <title>AJAX 登入範例</title>
    <link href="/Content/style.css" rel="stylesheet" />
    <script src="/Scripts/jquery-1.8.3.min.js"></script>
</head>
<body>
    <div class="loginCon">
        <h2><span>會員登入</span></h2>
        <form id="formData">
            <div class="inputBox">
                <input type="text" name="user" placeholder="帳號/手機" class="userId" />
            </div>
            <div class="inputBox">
                <input type="password" name="pwd" placeholder="密碼" class="passwordStyle" />
            </div>
            <div class="warn" style="display:none">帳號或密碼錯誤!</div>
            <div class="remember">
                <label><input type="checkbox" name="remembered" /> 自動登入</label>
            </div>
            <button type="button" class="loginBtn">登入</button>
        </form>
    </div>

<script>
$(function () {
    // Enter 送出
    $('.userId, .passwordStyle').on('keyup', function (e) {
        if (e.keyCode === 13) $('.loginBtn').trigger('click');
    });

    $('.loginBtn').on('click', function () {
        $('.warn').hide();
        var pwd = $('.passwordStyle').val();
        if (!pwd) { $('.warn').text('請輸入密碼').show(); return; }

        var data = $('#formData').serialize();
        $.post('/Login/CheckLoginInfo', data, function (res) {
            if (res.status === 1) {
                window.location.href = '/MemberCenter/Index';
            } else {
                $('.warn').text('帳號或密碼錯誤!').show();
            }
        }, 'json').fail(function () {
            $('.warn').text('系統忙碌,請稍後再試').show();
        });
    });
});
</script>
</body>
</html>

後端 Controller

using System;
using System.Web.Mvc;
using System.Web.Security;
using MyApp.Models;
using MyApp.Services;

namespace MyApp.Controllers
{
    public class LoginController : Controller
    {
        public ActionResult Index() => View();

        [HttpPost]
        public ActionResult CheckLoginInfo(string user, string pwd, string remembered)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(user) || string.IsNullOrWhiteSpace(pwd))
                    return Json(new { status = 0 });

                // 密碼雜湊(示範 MD5,生產環境請用 BCrypt)
                pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "md5").ToLower();

                // 查詢會員
                var account = MemberInfoService.GetMemberIdForCheck(user, pwd);
                if (account == null)
                    return Json(new { status = 0 });

                // 登入成功:寫入 Session
                FunSession.SetSession(account); // 自訂 Session 封裝

                // 記住我:發送 Cookie
                if (remembered == "on")
                {
                    var cookie = new HttpCookie("LoginInfo", account.Id.ToString()) { Expires = DateTime.Now.AddDays(3) };
                    Response.Cookies.Add(cookie);
                }
                else
                {
                    // 明確刪除 Cookie
                    var cookie = new HttpCookie("LoginInfo", "") { Expires = DateTime.Now.AddYears(-1) };
                    Response.Cookies.Add(cookie);
                }

                return Json(new { status = 1 });
            }
            catch (Exception ex)
            {
                // 記錄日誌
                return Json(new { status = 0, msg = "伺服器錯誤" });
            }
        }
    }
}

關鍵實作細節

  1. 表單序列化:$('#formData').serialize() 自動收集所有 name 屬性欄位,產生 user=xxx&pwd=yyy&remembered=on 字串。
  2. 模型繫結:MVC 自動將查詢字串對應到 Action 參數 (string user, string pwd, string remembered)。
  3. 密碼雜湊:使用 FormsAuthentication.HashPasswordForStoringInConfigFile(舊版相容),新專案建議改用 BCrypt.Net-Next 套件。
  4. Session 封裝:FunSession.SetSession(account) 將使用者物件序列化存入 Session,方便全站存取。
  5. Cookie 管理:remembered == "on" 判斷核取方塊狀態,設定 3 天效期或立即過期刪除。
  6. 錯誤處理:try-catch 捕獲例外,回傳統一格式 JSON,前端 .fail() 處理網路層錯誤。

安全性加強建議

  • 啟用 [ValidateAntiForgeryToken] 配合 @Html.AntiForgeryToken() 防 CSRF。
  • 密碼採用 BCrypt 或 Argon2,拒絕 MD5/SHA 系列。
  • 登入失敗計數 + 帳號暫時鎖定,防暴力破解。
  • 全站強制 HTTPS,Cookie 設定 Secure、HttpOnly、SameSite=Strict。

總結

此範例展示了 ASP.NET MVC 中 AJAX 登入的標準模式:前端無刷新提交 → 後端驗證回傳 JSON → 前端依狀態導向或提示。程式碼結構清晰、關注點分離,易於擴充為社群登入、雙因子驗證等進階功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved