๐ BaseController.cs Documentation
๐ Table of Contents
- Overview & Purpose
- Dependencies & Technologies
- Class: BaseController
- Key Functional Areas
- View Models & Data Models
- Helper Methods & Utilities
- Error Handling & Return Types
- Thirdโparty Integrations
- Sample Usage & Code Examples
- UML Class Diagram
- Conclusion
๐ง Overview & Purpose
BaseController is an ASP.NET Core MVC base class from which all application controllers inherit common behavior:
- Audit logging of every incoming request
- User context initialization, reading Azure AD details & database records
- ViewBag population for layout components (e.g., Department, Role, DisplayName)
- Central place to implement permission checks (commented-out stubs)
Location:
IrbyImaging.UI/Controllers/BaseController.cs
Author: kvamshi
Created: 05โ17โ2022
โ๏ธ Dependencies & Technologies
| Category | Package / Framework |
|---|---|
| .NET Core / ASP.NET Core | Microsoft.AspNetCore.Mvc, EntityFrameworkCore |
| Configuration | Microsoft.Extensions.Configuration |
| HTTP Context & Filters | Microsoft.AspNetCore.Http, Microsoft.AspNetCore.Mvc.Filters |
| Database Context | IrbyContext (EF Core DbContext) |
| Models & Services | IrbyImaging.Models, IrbyImaging.UI.Models |
| Repositories & Helpers | AuditRepository, AzureADRead, ActiveDirectoryService |
๐ Class: BaseController
namespace IrbyImaging.UI.Controllers
{
public class BaseController : Controller
{
private readonly IrbyContext _context;
private readonly IConfiguration _configuration;
// 1. Constructor
public BaseController(IrbyContext context, IConfiguration configuration) { ... }
// 2. Pre-Action Hook
public override void OnActionExecuting(ActionExecutingContext filterContext) { ... }
// 3. Audit Logger
public void AuditActivity(ActionExecutingContext filterContext, Employee emp) { ... }
}
}
1. Constructor
public BaseController(IrbyContext context, IConfiguration configuration)
{
_context = context;
_configuration = configuration;
}
- Purpose: Injects the EF Core database context and application configuration.
- Parameters:
IrbyContext context: access to DB sets (Employees, Audit logs, etc.).IConfiguration configuration: access toappsettings.jsonor environment variables.
2. Override: OnActionExecuting
โจ Pre-action filter that runs before any derived controller action:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// 1. Read user claims (Full name, email)
var fullname = User.Claims.ToList()[1].Value;
var email = User.Identity.Name;
// 2. Fetch Azure AD user details
var ad = new AzureADRead(_context, _configuration);
var res = ad.GetUserADList(email).Result; // department, title, full name
// 3. Fetch local Employee record
var username = email.Split("@")[0];
var employee = _context.Employees
.FirstOrDefault(e => e.WorkEmail == email)
?? _context.Employees
.FirstOrDefault(e => e.UserName == username);
// 4. Audit the request
AuditActivity(filterContext, employee);
// 5. Populate ViewBag for shared layout
ViewBag.Department = res.Department ?? "";
ViewBag.Role = res.Title ?? "";
ViewBag.DisplayName= res.FullName ?? "";
base.OnActionExecuting(filterContext);
}
Key actions:
- Retrieves Azure AD and database user info
- Calls
AuditActivity(...)to persist an audit log - Sets
ViewBagvalues for UI rendering in Razor views
Note: Commented-out code stubs exist for employee status checks & dynamic permission assignment.
3. Method: AuditActivity
๐ Logs user interactions in Audit table.
public void AuditActivity(ActionExecutingContext filterContext, Employee emp)
{
var audit = new AuditModel
{
UserEmail = filterContext.HttpContext.User.Identity.Name,
ControllerName = /* current controller */,
ActionName = /* current action */,
Area = /* MVC area if any */,
PageAccessed = filterContext.HttpContext.Request.Path,
IpAddress = filterContext.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(),
SessionId = filterContext.HttpContext.Session.Id,
LangId = filterContext.HttpContext.Session.GetInt32(AllSessionKeys.LangId)?.ToString() ?? "",
IsFirstLogin = filterContext.HttpContext.Session.GetString(AllSessionKeys.IsFirstLogin) ?? "",
Namespace = filterContext.ActionDescriptor.DisplayName,
UrlReferrer = filterContext.HttpContext.Request.GetTypedHeaders().Referer?.AbsoluteUri,
LoginStatus = "Active"
};
// Persist via repository
var repo = new AuditRepository(_context);
repo.InsertAuditLogs(audit, emp);
}
Data Recorded:
- UserEmail, Controller, Action, Area
- Session ID, Language, FirstLogin
- IP Address, Page Accessed, Referrer URL
- Timestamp (added by repository or DB)
๐ Key Functional Areas
- Authentication Context
- Reads the loggedโin user's claims & identity.
- Azure AD Integration
- Enriches with department, title, full name via
AzureADRead.
- Enriches with department, title, full name via
- Database Lookup
- Finds corresponding
Employeerecord.
- Finds corresponding
- Audit Logging
- Centralized
AuditActivityto persist every request.
- Centralized
- UI Data Binding
- Shares user metadata with all Razor views via
ViewBag.
- Shares user metadata with all Razor views via
- Permission Hooks (commented-out)
- Stubs for dynamic permission enforcement & termination checks.
๐ผ View Models & Data Models
| Model | Location | Purpose |
|---|---|---|
Employee |
IrbyImaging.Models |
HR/user details (Username, Email, Status) |
AuditModel |
IrbyImaging.UI.Models |
Data shape for audit logging |
IrbyContext |
IrbyImaging.BusinessLogic |
EF Core DB context for Employees, Audits |
AllSessionKeys |
IrbyImaging.UI.Helpers |
Session key constants (LangId, FirstLogin) |
๐ Helper Methods & Utilities
- AzureADRead
- Reads Azure AD graph for department/title via
_context&_configuration.
- Reads Azure AD graph for department/title via
- ActiveDirectoryService
- Placeholder for further AD operations (unused here).
- AuditRepository
- Encapsulates DB write logic for
AuditModel.
- Encapsulates DB write logic for
- AllSessionKeys
- Constants for session-based flags (language, first login).
โ ๏ธ Error Handling & Return Types
- Exceptions bubbling from Azure AD calls or EF Core queries will propagate up; no custom catch blocks in
BaseController. - Redirect Logic
- Commented-out redirection to
UnAuthorized/Indexfor terminated employees or insufficient permissions.
- Commented-out redirection to
- Return Values
OnActionExecutingisvoid; you may setfilterContext.Resultto shortโcircuit execution.
๐ Thirdโparty Integrations
- Azure Active Directory
- Via custom
AzureADReadservice to fetch user metadata.
- Via custom
- Entity Framework Core
- For database connectivity & audit persistence.
- ASP.NET Core MVC Filters
- Utilizes
OnActionExecutingfor cross-cutting concerns.
- Utilizes
๐ก Sample Usage & Code Examples
Deriving from BaseController
public class HomeController : BaseController
{
public HomeController(IrbyContext ctx, IConfiguration cfg)
: base(ctx, cfg) { }
public IActionResult Index()
{
// ะัั shared logic runs first (OnActionExecuting)
return View();
}
}
Audit Repository Insert (simplified)
public class AuditRepository
{
private readonly IrbyContext _ctx;
public AuditRepository(IrbyContext ctx) => _ctx = ctx;
public void InsertAuditLogs(AuditModel model, Employee emp)
{
_ctx.AuditLogs.Add(model);
_ctx.SaveChanges();
}
}
๐ UML Class Diagram
@startuml
class BaseController {
- IrbyContext _context
- IConfiguration _configuration
+ BaseController(IrbyContext, IConfiguration)
+ OnActionExecuting(ActionExecutingContext)
+ AuditActivity(ActionExecutingContext, Employee)
}
class AzureADRead
class ActiveDirectoryService
class AuditRepository
class Employee
class AuditModel
BaseController --> AzureADRead : uses
BaseController --> ActiveDirectoryService : uses
BaseController --> AuditRepository : uses
AuditRepository --> AuditModel
BaseController ..> Employee : references
@enduml
๐ Conclusion
BaseController provides a robust foundation for all MVC controllers in the IrbyImaging.UI project by:
- Centralizing authentication & user context logic
- Automating audit log creation
- Preparing UI-specific data (
ViewBag) for shared layouts - Outlining hooks for advanced permission handling
Controllers inheriting from BaseController gain cross-cutting capabilities without cluttering individual action methods. Enjoy building on this solid base! ๐