Search code examples
c#aop

How to pass name of parameters to aspect methods


Index and aspect method that used for logging below.

Action:

[LogAspect]
public ActionResult Index(int projectId)
{
    ...
    return PartialView(model);
}

Aspect method:

[Serializable]
public class LogAspect : OnMethodBoundaryAspect
{
    public override void OnExit(MethodExecutionArgs args)
    {
        var parameters = JsonConvert.SerializeObject(args.Arguments.ToList());
        string message = string.Format("Releted method parameters:{0}", parameters);
        Logger.Info(string.Format("Controller:{0}, Action:{1}", args.Method.DeclaringType.FullName, args.Method.ToString()), message);
        base.OnExit(args);
    }
}

I can get the value of projectid as integer like [1]. But as you guess I am using this aspect method to log this information and it doesn't make sense if there isn't the name of the parameter (it's written to database) so I want to get the parameter like [projectId:1] etc.

This would be easy with reflection if I was using logger in controller but I am doing this process in aspect method.


Solution

  • Arguments contains the values only. However, you do have the usual reflection interface in Method:

    args
      .Method
      .GetParameters()
      .Select((p, i) => new { Name = p.Name, Value = args.Arguments[i] });