我正在尝试添加日志记录功能以保存到我的 SQL Server 数据库。我尝试创建 ActionFilter 类并应用于我的控制器之一,但不起作用。
我想捕获用户 ID、IP 地址、控制器和操作访问以及时间戳。我缺少什么?
AuditAttribute Action Filter class
public class AuditAttribute : ActionFilterAttribute
{
private readonly ApplicationDbContext _db;
//Inject ApplicationDBContext
public AuditAttribute(ApplicationDbContext db)
{
_db = db;
}
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//Stores the Request in an Accessible object
var request = filterContext.HttpContext.Request;
//Generate an audit
Portal_Logger audit = new Portal_Logger()
{
teacherNRIC = filterContext.HttpContext.User.Identity.Name,
IPAddress = Convert.ToString(ipHostInfo.AddressList.FirstOrDefault(address => address.AddressFamily == AddressFamily.InterNetwork)),
ControllerAccess = (string)filterContext.RouteData.Values["controller"],
Timestamp = DateTime.Now,
};
public DbSet<Portal_Logger> Portal_LoggerDBSet { get; set; }
//Store objects to database
_db.Portal_LoggerDBSet.Add(audit);
_db.SaveChanges();
base.OnActionExecuting(filterContext);
}
}
}
Home controller class
[AuditAttribute]
public class HomeController : Controller
{ ..content of controller
}
Portal_logger model class
public class Portal_Logger
{
[Key]
public int LoggerId { get; set; }
[StringLength(10)]
public string userid{ get; set; }
[StringLength(50)]
public string IPAddress { get; set; }
[StringLength(50)]
public string ControllerAccess { get; set; }
public DateTime? Timestamp { get; set; }
}
请参阅附图所示的错误消息错误信息截图 https://i.stack.imgur.com/iETGt.png
我尝试了一下,出现了新问题。在此输入图像描述 https://i.stack.imgur.com/94XCV.png
我尝试过这个方法也行不通。
[AuditActionFilter] -> 错误消息(AuditActionFilter 不是属性类)
public class HomeController : Controller
{
}
我尝试了这个方法但仍然不起作用。
[AuditActionFilter] - error message -> "AuditActionFilter" is not an
public class HomeController : Controller
{
}
我已将 services.AddMVC 添加到startup.cs
services.AddMvc(options => options.Filters.Add(typeof(AuditActionFilter)));
这是 AuditActionFilter.cs
public class AuditActionFilter : IActionFilter
{
private readonly ApplicationDbContext _db;
public AuditActionFilter(ApplicationDbContext db)
{
_db = db;
}
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
public void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
Portal_Logger audit = new Portal_Logger()
{
teacherNRIC = filterContext.HttpContext.User.Identity.Name,
IPAddress = Convert.ToString(ipHostInfo.AddressList.FirstOrDefault(address => address.AddressFamily == AddressFamily.InterNetwork)),
ControllerAccess = (string)filterContext.RouteData.Values["controller"],
Timestamp = DateTime.Now,
};
//Store objects to database
_db.Portal_LoggerDBSet.Add(audit);
_db.SaveChanges();
}
public void OnActionExecuted(ActionExecutedContext context)
{
// do something after the action executes or leave it empty
}
}