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



我试图从异常过滤器中获取方法名称和类名称,但无法这样做。我想是因为使用了异步方法。我得到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;
}
}

我找到了一个方法来得到它。我提供答案是为了帮助有类似情况的人。

我从中找到了答案问题

请查找下面的代码

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;
}
}

对于异步和非异步函数都可以正常工作。

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

最新更新