在用户后台我们不可能每步操作都要重新写一段代码来判断session是否存在。对于此可以新建一个类重写OnActionExecuting方法,然后其他的用户操作类都继承这方法。
新建一个BaseUserController
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace NerdDinnerTest.Controllers { public class BaseUserController : Controller { protected override void OnActionExecuting(ActionExecutingContext filterContext) { HttpContextBase context = filterContext.HttpContext; if (context.Session["user"] == null) { HttpContext.Response.Redirect("/login.htm"); } base.OnActionExecuting(filterContext); } } }
在其他controll类里面继承这方法
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace NerdDinnerTest.Controllers
{
public class UserController :BaseUserController
{
//
// GET: /User/
public ActionResult Main()
{
dynamic user = Session["user"];
ViewData["username"] = user.userName;
ViewData["password"] = user.password;
return View();
}
}
}