Margaal

Margaal

  • NA
  • 139
  • 88.1k

Best ways to track user activities in my ASP.NET Core app

Jul 11 2019 5:07 AM
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


  1. public class ActivitiesAttribute : ResultFilterAttribute  
  2.     {  
  3.         private string _description;  
  4.   
  5.         public ActivitiesAttribute(string description)  
  6.         {  
  7.             _description = description;  
  8.         }  
  9.   
  10.         public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)  
  11.         {  
  12.             Debug.WriteLine($"===User : {context.HttpContext.User.Identity.Name}, description : {_description}, Date {DateTime.Now.ToString()}");  
  13.             return base.OnResultExecutionAsync(context, next);  
  14.         }  
  15.     }  

 
My Controller
 
  1. [Authorize]  
  2.     public class ProductsController : Controller  
  3.     {  
  4.         private readonly ApplicationDbContext _context;  
  5.   
  6.         public ProductsController(ApplicationDbContext context)  
  7.         {  
  8.             _context = context;  
  9.         }  
  10.   
  11.         // GET: Products  
  12.         [Activities("Products List")]  
  13.         public async Task<IActionResult> Index()  
  14.         {  
  15.             return View(await _context.Products.ToListAsync());  
  16.         }  
  17.   
  18.         // GET: Products/Details/5  
  19.         [Activities("Product Detail")]  
  20.         public async Task<IActionResult> Details(int? id)  
  21.         {  
  22.             if(id == null)  
  23.             {  
  24.                 return NotFound();  
  25.             }  
  26.   
  27.             var product = await _context.Products  
  28.                 .FirstOrDefaultAsync(m => m.Id == id);  
  29.             if(product == null)  
  30.             {  
  31.                 return NotFound();  
  32.             }  
  33.   
  34.             return View(product);  
  35.         }  
  36.   
  37.         // GET: Products/Create  
  38.         [Activities("Product Creation")]  
  39.         public IActionResult Create()  
  40.         {  
  41.             return View();  
  42.         }  
  43.      ....  
  44. }  
 

Answers (5)