使用 ActionFilter 进行 ASP.NET Core 日志记录

问题描述 投票:0回答:4

我正在尝试添加日志记录功能以保存到我的 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; }

}

请参阅附图所示的错误消息 错误信息截图

我尝试过,但遇到了新问题。 在此输入图片描述

这个方法我也试过了,还是不行。 [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
    }

}
c# asp.net-core logging action-filter
4个回答
2
投票

要在特定方法或控制器上使用

AuditAttribute
,您可以尝试
ServiceFilterAttribute
TypeFilterAttribute

以下是可用的两个选项:

选项1

使用

TypeFilterAttribute

[TypeFilter(typeof(AuditAttribute))]
public class HomeController : Controller

选项2

使用

ServiceFilterAttribute

  1. AuditAttribute
     注册 
    Startup.cs

     services.AddScoped<AuditAttribute>();
    
  2. 使用

    AuditAttribute

     [ServiceFilter(typeof(AuditAttribute))]
     public class HomeController : Controller
    

0
投票

发生错误是因为您的属性上有一个“DbContext”参数,但在将其应用到控制器时没有提供它?

public AuditAttribute(ApplicationDbContext db)
{
    _db = db;
}

0
投票

如何在 Action 过滤器中使用 DI 描述如下: https://www.c-sharpcorner.com/blogs/custom-filter-in-mvc-or-logging-using-mvc-filter

文章简短:

为所有控制器启用:

starup.cs:

services.AddMvc(options =>  
{  
   options.Filters.Add(typeof(AuditAttribute));  
});

仅对一个控制器启用:

starup.cs:

services.AddScoped<AuditAttribute>();

接下来放置在控制器或操作方法上:

[ServiceFilter(typeof(AuditAttribute))] 

0
投票

要使用该属性而不必求助于 [TypeFilter(typeof(AuditAttribute))] 或 [ServiceFilter(typeof(AuditAttribute))] ,应该可以通过使用 filterContext.HttpContext.RequestServices.GetService 而不是通过构造函数。

public class AuditActionFilter : IActionFilter
{

public AuditActionFilter(){}

IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());

public void OnActionExecuting(ActionExecutingContext filterContext)
{
    ApplicationDbContext _db = filterContext.HttpContext.RequestServices.GetService<ApplicationDbContext>();

    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();
}
© www.soinside.com 2019 - 2024. All rights reserved.