如何获取在 OnExceptionAsync c# 中引发异常的方法名称

How to get the method name that originated the exception in OnExceptionAsync c#

我试图在我的异常过滤器中获取方法名称和 class 名称,但无法这样做。我认为是因为使用了异步方法。我将 MoveNext 作为方法而不是实际的方法名称。

请在下面找到代码

 public class ExceptionFilter : ExceptionFilterAttribute
    {
        /// <summary>
        /// Exception filter
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken)
        {
            
            var s = new StackTrace(context.Exception);
            var methodname=s.GetFrame(0).GetMethod().Name;


            Logger.LogError(context.Exception, context.Exception.Message);
            
            context.Response = context.Request.CreateResponse(HttpStatusCode.OK, res);
            return Task.CompletedTask;
        }

      }

我搜索了很多但找不到任何答案。 任何帮助将不胜感激。

您可以像这样创建一个扩展,并在 async 方法的情况下获取详细信息。

public static class SampleExtension
{
    public static string GetOriginMethod(this MethodBase methodBase, [CallerMemberName] string memberName = "")
    {
        return memberName;
    }
}

我找到了一种方法 it.I 我正在提供答案,以便它可以帮助有类似情况的人。

我从这里找到了答案 question

请在下面找到代码

 public class ExceptionFilter : ExceptionFilterAttribute
    {
        /// <summary>
        /// Exception filter
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken)
        {
            
            Logger.LogError(context.Exception, context.Exception.Message);

            var s = new StackTrace(context.Exception);
            var r = s.GetFrame(0);
            UtilityDAL.WriteExceptionLog("None", context.Exception, GetMethodName(r.GetMethod()), GetClassName(r.GetMethod()));

            context.Response = context.Request.CreateResponse(HttpStatusCode.OK, res);
            return Task.CompletedTask;
        }

        private string GetMethodName(System.Reflection.MethodBase method)
        {
            string _methodName = method.DeclaringType.FullName;

            if (_methodName.Contains(">") || _methodName.Contains("<"))
            {
                _methodName = _methodName.Split('<', '>')[1];
            }
            else
            {
                _methodName = method.Name;
            }

            return _methodName;
        }

        private string GetClassName(System.Reflection.MethodBase method)
        {
            string className = method.DeclaringType.FullName;

            if (className.Contains(">") || className.Contains("<"))
            {
                className = className.Split('+')[0];
            }
            return className;
        }
    }

它适用于异步和非异步函数。

注意:我不确定这是否适用于所有情况,但到目前为止它对我来说效果很好。