在ASP.NET MVC中,BaseController是一个常见的基类设计模式,用于封装多个控制器共用的逻辑或属性。以下是关于BaseController中对象使用的详细解析:
BaseController继承自System.Web.Mvc.Controller
,其他控制器通过继承它来复用代码。其核心作用包括:
OnActionExecuting
等方法实现全局逻辑(如权限校验)。public class BaseController : Controller
{
// 共享对象(如数据库上下文)
protected ApplicationDbContext _dbContext;
protected UserInfo _currentUser;
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
// 初始化共享对象
_dbContext = new ApplicationDbContext();
_currentUser = Session["CurrentUser"] as UserInfo;
// 示例:全局权限校验
if (_currentUser == null)
{
filterContext.Result = RedirectToAction("Login", "Account");
}
}
protected override void Dispose(bool disposing)
{
if (disposing && _dbContext != null)
{
_dbContext.Dispose();
}
base.Dispose(disposing);
}
}
// 派生控制器
public class HomeController : BaseController
{
public ActionResult Index()
{
// 直接使用基类中的_dbContext和_currentUser
var posts = _dbContext.Posts.Where(p => p.UserId == _currentUser.Id).ToList();
return View(posts);
}
}
_dbContext
未及时释放,导致内存泄漏。Dispose
方法手动释放资源(见示例代码)。_dbContext
实例引发冲突。static
,或使用依赖注入(如ASP.NET Core的Scoped生命周期)。_currentUser
为null
。OnActionExecuting
逻辑覆盖所有场景,或使用属性懒加载:OnActionExecuting
逻辑覆盖所有场景,或使用属性懒加载:OnException
方法全局捕获异常。在ASP.NET MVC 5或Core中,更推荐通过构造函数注入依赖:
public class BaseController : Controller
{
protected readonly ILogger _logger;
protected readonly ApplicationDbContext _dbContext;
public BaseController(ILogger logger, ApplicationDbContext dbContext)
{
_logger = logger;
_dbContext = dbContext;
}
}
// 注册服务(通常在Global.asax或Startup.cs)
container.Register<ApplicationDbContext>(LifeTime.PerRequest);
container.Register<ILogger, FileLogger>();
BaseController是ASP.NET MVC中实现代码复用的重要手段,合理使用可提升开发效率,但需注意对象生命周期和线程安全。现代项目中,结合依赖注入(DI)能进一步解耦代码。