本篇解析 `web.config` 核心配置區段,並詳細說明如何利用 ASP.NET MVC 的 `ActionFilterAttribute` 實現輕量級權限控制,替代笨重的 Membership 系統。
<connectionStrings>
<add name="ABConnection"
connectionString="Data Source=|DataDirectory|AlumniBook.sdf"
providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters><parameter value="4.0" /></parameters>
</defaultConnectionFactory>
</entityFramework>
第 70 行左右的 `
MVC 無 WebForm 的控制項拖拉模式,權限驗證需在 Action 執行前攔截。選擇 `Filter`(動作過濾器)而非基底 Controller 繼承,原因:
using System.Web.Mvc;
using AlumniBook.Models;
using AlumniBook.Ensleep;
namespace AlumniBook.Filters
{
public class IsLogedAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// 若 Session 中無使用者資訊,導向登入頁
if (filterContext.HttpContext.Session["CurrentUser"] == null)
{
// 保存原請求 URL,登入後可導回
string returnUrl = filterContext.HttpContext.Request.Url.PathAndQuery;
filterContext.Result = new RedirectResult(
$"/Log/Login?returnUrl={HttpUtility.UrlEncode(returnUrl)}");
}
base.OnActionExecuting(filterContext);
}
}
}
public class IsAdminAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var user = filterContext.HttpContext.Session["CurrentUser"] as User;
if (user == null || !user.IsAdmin)
{
filterContext.Result = new RedirectResult("/Error/UnAuthorized");
}
base.OnActionExecuting(filterContext);
}
}
[IsLoged] // 整個 Controller 需登入
public class ClassController : Controller
{
[IsAdmin] // 僅此 Action 需管理員
public ActionResult Delete(int id) { ... }
public ActionResult Index(string className) { ... } // 一般登入用戶可存取
}
public static class CryptoHelper
{
public static string GetMD5(string input)
{
using (var md5 = System.Security.Cryptography.MD5.Create())
{
byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
return BitConverter.ToString(data).Replace("-", "").ToLower();
}
}
}
public static class CookieHelper
{
public static void SetCookie(string name, string value, int days)
{
var cookie = new HttpCookie(name, value) { Expires = DateTime.Now.AddDays(days) };
HttpContext.Current.Response.Cookies.Add(cookie);
}
public static void RemoveCookie(string name)
{
if (HttpContext.Current.Request.Cookies[name] != null)
{
var cookie = new HttpCookie(name) { Expires = DateTime.Now.AddDays(-1) };
HttpContext.Current.Response.Cookies.Add(cookie);
}
}
}
精簡的 `web.config` 搭配自訂 `ActionFilter`,即可構建清晰、可維護的權限體系。避免 Membership 的過度設計,讓專案專注於業務邏輯。下一篇將展示系統整體架構圖與前台需求設計。