How to log information in MVC asp.net 3.0 on the controller level rather then wrting the samething on each action.

Amir Saleem 41 Reputation points
2021-01-13T13:40:39.973+00:00

Hello All,

I am using MVC asp.net core 3.1 application. I am implementing the log. I do have some informational logs that log some messages but then I want to log information everything each action is called with the information with controller and action.
I have tried many solution out there but I am getting issues. I tried filters on controller level but my code breaks. If anyone can point me to the solution.

Thanks

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,345 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rena Ni - MSFT 2,066 Reputation points
    2021-01-14T06:15:43.08+00:00

    Hi @Amir Saleem ,

    If you want to log the infomation before action is called,you could custom ActionFilter to meet your requirement.

    Here is a working demo:

    1.Custom ActionFilter:

    public class CustomFilter: IActionFilter  
    {  
        private readonly ILogger<CustomFilter> _logger;  
        public CustomFilter(ILogger<CustomFilter> logger)  
        {  
            _logger = logger;  
        }  
        public void OnActionExecuting(ActionExecutingContext context)  
        {  
            var controllerName = ((Microsoft.AspNetCore.Mvc.ControllerBase)context.Controller)  
                                    .ControllerContext  
                                    .ActionDescriptor  
                                    .ControllerName;  
            var actionName = ((Microsoft.AspNetCore.Mvc.ControllerBase)context.Controller)  
                                    .ControllerContext  
                                    .ActionDescriptor  
                                    .ActionName;  
            _logger.LogInformation("Get into "+actionName+" action in "+ controllerName + " controller");  
        }  
        public void OnActionExecuted(ActionExecutedContext context)  
        {  
        }  
    }  
    

    2.Register the filter:

    services.AddControllers(  
        config =>  
        {  
            config.Filters.Add<CustomFilter>();  
        });  
    

    3.Result:
    56289-bc.gif


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,
    Rena

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful