在ASP.NET Core应用程序中使用拦截器时,需要在异步方法调用的返回类型上使用Task
以下是一个示例拦截器,该拦截器将在方法执行前后记录执行时间,并返回执行结果:
public class TimingInterceptor : IInterceptor
{
private readonly ILogger _logger;
public TimingInterceptor(ILogger logger)
{
_logger = logger;
}
public void Intercept(IInvocation invocation)
{
var stopwatch = Stopwatch.StartNew();
invocation.Proceed();
stopwatch.Stop();
var methodName = invocation.Method.Name;
var result = invocation.ReturnValue;
if (result is Task task)
{
task.Wait();
dynamic taskResult = task.GetType().GetProperty("Result").GetValue(task, null);
_logger.LogInformation($"{methodName} executed in {stopwatch.ElapsedMilliseconds}ms with result: {taskResult}");
}
else
{
_logger.LogInformation($"{methodName} executed in {stopwatch.ElapsedMilliseconds}ms with result: {result}");
}
}
}
在上面的示例中,如果方法返回Task类型,我们首先等待任务完成,然后使用反射来获取结果并记录日志。否则,我们直接记录返回值。