📄 AuditFilterAttribute Documentation
Location:
IrbyImaging/Filters/AuditFilterAttribute.cs
📑 Table of Contents
- Overview & Purpose
- Dependencies & Technologies
- Class Diagram (UML)
- Key Functional Areas
- Data Model:
AuditModel - Method Details
- Usage & Integration
- Error Handling & Return Types
- Third‑party Integrations
- Sample Code Snippets
- Conclusion
🔍 1. Overview & Purpose
AuditFilterAttribute is an ASP.NET Core Action Filter designed to automatically record audit‑trail entries for each MVC/WebAPI action execution.
- Captures who accessed what resource, when, and from where (IP address, referrer, session details).
- Persists this data via an
IAuditRepository(e.g., backed by EF Core). - Ensures centralized, consistent auditing without polluting controller code.
Key Benefits:
- ✅ Centralized logging of user activity
- 🔒 Security & compliance support (e.g., GDPR, internal audits)
- 📊 Simplified reporting & analytics
⚙️ 2. Dependencies & Technologies
| Category | Component/Library |
|---|---|
| Framework | ASP.NET Core MVC / WebAPI |
| Filters | Microsoft.AspNetCore.Mvc.Filters.ActionFilterAttribute |
| HTTP Context | Microsoft.AspNetCore.Http.IHttpContextAccessor |
| Data Access (Repo) | Custom IAuditRepository (likely EF Core–backed) |
| Models | IrbyImaging.UI.Models.AuditModel |
| Session & Headers | Microsoft.AspNetCore.Http.Headers |
📐 3. Class Diagram (UML)
classDiagram
class AuditFilterAttribute {
- IAuditRepository _auditRepository
- IHttpContextAccessor _httpContextAccessor
+ AuditFilterAttribute(IHttpContextAccessor, IAuditRepository)
+ override void OnActionExecuting(ActionExecutingContext)
}
class AuditModel {
+ string UserEmail
+ string Area
+ string LangId
+ string IsFirstLogin
+ string SessionId
+ string IpAddress
+ string PageAccessed
+ string LoginStatus
+ string ControllerName
+ string ActionName
+ string UrlReferrer
}
class IAuditRepository {
<<interface>>
+ void InsertAuditLogs(AuditModel)
}
AuditFilterAttribute --> IAuditRepository
AuditFilterAttribute --> IHttpContextAccessor
AuditFilterAttribute --> AuditModel
IAuditRepository ..> AuditModel
💡 4. Key Functional Areas
-
Injection & Initialization
IHttpContextAccessorto access request/session details.IAuditRepositoryfor persisting audit entries.
-
OnActionExecuting
- Fires before every controller action.
- Gathers request metadata:
- User identity (
User.Identity.Name) - Controller & Action names
- Area (if MVC Areas are in use)
- Session variables:
LangId,IsFirstLogin,SessionId - IP Address
- URL accessed & referrer
- Login status (hard‑coded
"Active"here)
- User identity (
- Constructs an
AuditModelinstance and inserts it via_auditRepository.
-
Extensibility
- Can be extended to capture more headers, body content, or response details.
- Swap out
IAuditRepositoryimplementation (e.g., SQL, NoSQL).
📊 5. Data Model: AuditModel
Namespace:
IrbyImaging.UI.Models
| Property | Type | Description |
|---|---|---|
UserEmail |
string | Authenticated user's email/username |
Area |
string | MVC Area name (if any) |
LangId |
string | Current language identifier (session) |
IsFirstLogin |
string | Flag indicating first login (session) |
SessionId |
string | ASP.NET Core session identifier |
IpAddress |
string | Client's remote IP address |
PageAccessed |
string | Requested URL path |
LoginStatus |
string | e.g., "Active" |
ControllerName |
string | Name of the controller being executed |
ActionName |
string | Name of the action being executed |
UrlReferrer |
string | Full URL of the referrer (if available) |
🛠️ 6. Method Details
OnActionExecuting
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// 1️⃣ Initialize the audit entry
var objaudit = new AuditModel
{
UserEmail = filterContext.HttpContext.User.Identity.Name,
ControllerName = ((ControllerBase)filterContext.Controller)
.ControllerContext.ActionDescriptor.ControllerName,
ActionName = ((ControllerBase)filterContext.Controller)
.ControllerContext.ActionDescriptor.ActionName,
PageAccessed = filterContext.HttpContext.Request.Path,
LoginStatus = "Active"
};
// 2️⃣ Session values
objaudit.LangId = filterContext.HttpContext.Session.GetInt32(AllSessionKeys.LangId)?.ToString() ?? "";
objaudit.IsFirstLogin = filterContext.HttpContext.Session.GetString(AllSessionKeys.IsFirstLogin) ?? "";
objaudit.SessionId = filterContext.HttpContext.Session.Id;
// 3️⃣ MVC Area (if present)
var rv = ((ControllerBase)filterContext.Controller).ControllerContext.ActionDescriptor.RouteValues;
if (rv.TryGetValue("area", out var area) && !string.IsNullOrEmpty(area))
objaudit.Area = area;
// 4️⃣ IP Address & Referrer
if (_httpContextAccessor.HttpContext != null)
objaudit.IpAddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress?.ToString();
var header = filterContext.HttpContext.Request.GetTypedHeaders();
objaudit.UrlReferrer = header.Referer?.AbsoluteUri;
// 5️⃣ Persist audit log
_auditRepository.InsertAuditLogs(objaudit);
}
Step-by-step breakdown:
- Create a new
AuditModelinstance. - Extract core data: user, controller/action names, requested path.
- Retrieve session keys via
HttpContext.Session. - Read network details from
IHttpContextAccessor. - Insert the audit record through
IAuditRepository.
🔗 7. Usage & Integration
7.1 Registration in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Register the HTTP context accessor
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Register your audit repository
services.AddScoped<IAuditRepository, SqlAuditRepository>();
// Add controllers and apply the filter globally
services.AddControllers(options =>
{
options.Filters.Add<AuditFilterAttribute>();
});
}
7.2 Applying Per‑Controller or Action
[ServiceFilter(typeof(AuditFilterAttribute))]
public class PatientController : ControllerBase
{
public IActionResult List() { … }
}
⚠️ 8. Error Handling & Return Types
- Exceptions within
OnActionExecuting—such as session or DB errors—will bubble up and typically result in a 500 Internal Server Error. - Best Practice: Surround repository calls with
try/catchinside the filter or implement global exception handling/middleware for graceful degradation.
🌐 9. Third‑party Integrations
- Entity Framework Core — likely used inside the
IAuditRepositoryfor persistingAuditModel. - ASP.NET Core Session — for retrieving language & login flags.
- HTTP Context / Headers — for IP/referrer extraction.
🖥️ 10. Sample Code Snippets
Sample IAuditRepository Implementation
public class SqlAuditRepository : IAuditRepository
{
private readonly AuditDbContext _context;
public SqlAuditRepository(AuditDbContext context) => _context = context;
public void InsertAuditLogs(AuditModel model)
{
var entity = new AuditEntity { /* map from model */ };
_context.Audits.Add(entity);
_context.SaveChanges();
}
}
Example Audit Entry in Database
| Id | UserEmail | ControllerName | ActionName | PageAccessed | IpAddress | LoginStatus | CreatedOn |
|---|---|---|---|---|---|---|---|
| 123 | jane.doe@corp |
Home |
Index |
/home/index |
192.168.0.12 |
Active |
2023-07-15 12:34 |
🏁 11. Conclusion
The AuditFilterAttribute provides a lightweight, reusable, and centralized mechanism for capturing comprehensive audit data across all MVC/WebAPI endpoints. By simply registering the filter and repository, you automatically gain:
- 🔍 Visibility into user activity
- 🛡️ Enhanced security & compliance
- 📈 Actionable analytics
Leverage this filter as the foundation of your application’s auditing strategy, and extend it to suit your organization’s specific requirements!
Happy coding & secure auditing! 🚀