Search code examples
c#asp.net-coreasp.net-core-webapipostsharp

How to use PostSharp LoggingAspect in controller?


I am trying to execute some logging logic after a method is done executing. So, I used the basic example described here by Postsharp as follows:

[PSerializable]
public class LoggingAspect : OnMethodBoundaryAspect
{
  public override void OnExit(MethodExecutionArgs args)
  {
     Console.WriteLine("The {0} method has exited.", args.Method.Name);
  }     
}

Then, I try to use this attribute LoggingAspect on different methods. It works on all methods except those in the controller class like the following:

[ApiController]
    [Route("[controller]/[action]")]
    public class HomeController : ControllerBase
    {
        [LoggingAspect]
        [HttpGet]
        public IEnumerable<Student> Get(string number, int? year)
        {
            ...
        }
    }

I expected the attribute LoggingAspect to work on all methods, however it did not work in the controller. Am I missing something?


Solution

  • It turns out I was not referencing Postsharp in the project I was using the LoggingAspect attribute in. It wasn't obvious at first as there were no build or runtime errors in that project.