asp.net mvc中的使用者登入驗證過濾器

lightwing發表於2021-09-09

在WEB專案中建立 類:
public class LoginFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//HttpContext.Current.Response.Write("OnActionExecuting:正要準備執行Action的時候但還未執行時執行
");
if (HttpContext.Current.Session"admin" == null)
{
//HttpContext.Current.Response.Write("js程式碼");
//HttpContext.Current.Response.End();
//return;

            var context = new ContentResult();
            context.Content = "
"); } public override void OnResultExecuting(ResultExecutingContext filterContext) { // HttpContext.Current.Response.Write("OnResultExecuting:OnResultExecuting也和OnActionExecuted一樣,但前者是在後者執行完後才執行
"); } public override void OnResultExecuted(ResultExecutedContext filterContext) { // HttpContext.Current.Response.Write("OnResultExecuted:是Action執行完後將要返回ActionResult的時候執行
"); } }

使用方法,直接在控制裡方法外面寫,如:
[LoginFilter]
public ActionResult Add()
{
Model.Userinfo loginuser = base.GetLoginUser();
Model.Product pro = new Model.Product() { userid = loginuser.id, username = loginuser.username };
return View(pro);
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/3407/viewspace-2799761/,如需轉載,請註明出處,否則將追究法律責任。

相關文章