设计一个验证用户身份是否登陆的基类BaseController
/// <summary> /// 所有需要进行登录控制的控制器基类 /// </summary> public class BaseController : Controller { /// <summary> /// 当前登录的用户属性 /// </summary> public UserInfo CurrentUserInfo { get; set; } /// <summary> /// 重新基类在Action执行之前的事情 /// </summary> /// <param name="filterContext">重写方法的参数</param> protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); //得到用户登录的信息 CurrentUserInfo = Session["UserInfo"] as UserInfo; //判断用户是否为空 if (CurrentUserInfo == null) { Response.Redirect("/Login/Index"); } } protected override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); //错误记录 WHC.Framework.Commons.LogTextHelper.Error(filterContext.Exception); // 当自定义显示错误 mode = On,显示友好错误页面 if (filterContext.HttpContext.IsCustomErrorEnabled) { filterContext.ExceptionHandled = true; this.View("Error").ExecuteResult(this.ControllerContext); } } ........................ }
有了这个基类,我们在主页的Home控制类,就可以使用用户信息对象了进行操作了,而且必须要求客户登陆了
public class HomeController : BaseController { public ActionResult Index() { if (CurrentUserInfo != null) { ViewBag.FullName = CurrentUserInfo.FullName; ViewBag.Name = CurrentUserInfo.Name; } return View(); } ................ }
时间: 2024-09-29 23:35:51