Currently, to track user activities, I create custom
filter attribute which based on ResultFilterAttribute. It's worked for me, but I want to know if there is no better way to perform this? Because, the documentation of .NET Core filter recommends "avoid creating and using filters purely for logging purposes."
Please give me your opinion.
My Custom Attribute
- public class ActivitiesAttribute : ResultFilterAttribute
- {
- private string _description;
-
- public ActivitiesAttribute(string description)
- {
- _description = description;
- }
-
- public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
- {
- Debug.WriteLine($"===User : {context.HttpContext.User.Identity.Name}, description : {_description}, Date {DateTime.Now.ToString()}");
- return base.OnResultExecutionAsync(context, next);
- }
- }
My Controller
- [Authorize]
- public class ProductsController : Controller
- {
- private readonly ApplicationDbContext _context;
-
- public ProductsController(ApplicationDbContext context)
- {
- _context = context;
- }
-
-
- [Activities("Products List")]
- public async Task<IActionResult> Index()
- {
- return View(await _context.Products.ToListAsync());
- }
-
-
- [Activities("Product Detail")]
- public async Task<IActionResult> Details(int? id)
- {
- if(id == null)
- {
- return NotFound();
- }
-
- var product = await _context.Products
- .FirstOrDefaultAsync(m => m.Id == id);
- if(product == null)
- {
- return NotFound();
- }
-
- return View(product);
- }
-
-
- [Activities("Product Creation")]
- public IActionResult Create()
- {
- return View();
- }
- ....
- }