Asp.net core 如何在ASP Core 5中获取异常中的方法名和行号

Asp.net core 如何在ASP Core 5中获取异常中的方法名和行号,asp.net-core,exception,try-catch,ex,method-names,Asp.net Core,Exception,Try Catch,Ex,Method Names,我想在发生错误时获取方法名和行号,我使用的是Core 5 try { //My code } catch (Exception ex) { _logger.LogError(ex, "Method Name / Line Number"); } 更新: 我找到了这样的解决方案: _logger.LogError(ex, "\

我想在发生错误时获取方法名和行号,我使用的是Core 5

        try
        {
           //My code
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Method Name / Line Number");
        }
更新:

我找到了这样的解决方案:

_logger.LogError(ex, "\n=> ex Error: " + ex + "\n=> Action Name: " + ex.TargetSite.ReflectedType.Name + "\n=> Error Message: " + ex.Message + "\n=> Line Number: " + ex.LineNumber());

对异常的
ToString()
的简单调用将为您提供所需的完整信息。例如,当我们运行以下代码时:

public static void Main()
{
    try
    {
        //my code
        throw new ArgumentException();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}
输出有点像:

System.ArgumentException: Value does not fall within the expected range.
   at ConsoleApp.Program.Main() in C:\Users\USER\source\Playground\ConsoleApp1\Program.cs:line 20
其中
Main()
是方法名,20是行号

要获得所需的格式,我们可以在异常周围编写一个包装器,并从中获取行号:

using System;
using System.Reflection;

namespace ConsoleApp
{
    class Program
    {
        public static void Main()
        {
            try
            {
                //my code
                throw new ArgumentException();
            }
            catch (Exception ex)
            {
                Console.WriteLine(MethodBase.GetCurrentMethod().Name + "/" + GetLineNumber(ex));
            }
        }

        public static int GetLineNumber(Exception ex)
        {
            var lineNumber = 0;
            const string lineSearch = ":line ";
            var index = ex.StackTrace.LastIndexOf(lineSearch);
            if (index != -1)
            {
                var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
                if (int.TryParse(lineNumberText, out lineNumber))
                {
                }
            }
            return lineNumber;
        }
    }
}
注意:在extract line方法中,我们获取的是最顶层的异常。当我们的堆栈跟踪中有一系列异常时,这就很方便了