How get current method name in API application

Binumon George 161 Reputation points
2023-07-25T11:02:11.68+00:00
Hi All,
         I want to log the current method name to a database table in an API application. However, when I use the following code "System.Reflection.MethodBase.GetCurrentMethod().Name", I receive "MoveNext" instead of the Method name. 

Please let me know how we may obtain the right method name. According to the code below, I'm anticipating "Statuses" as the method name.


 [HttpGet("Statuses")]
        public async Task<IActionResult> GetPaymentStatuses()
        {
            
            string methodname=System.Reflection.MethodBase.GetCurrentMethod().Name.toString();
            logger.saveLog(token, GetType().Namespace, 1, methodname + "-Enter");
        }
Developer technologies ASP.NET ASP.NET Core
Developer technologies C#
{count} votes

3 answers

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2023-07-25T12:59:16.0366667+00:00

    In case of async, try a different approach:

    string name = null;
    for( int i = 0; name == null; ++i )
    {
        StackFrame sf = new StackFrame( skipFrames: i, needFileInfo: false );
        HttpGetAttribute a = sf.GetMethod( ).GetCustomAttribute<HttpGetAttribute>( );
        name = a?.Template;
    }
    
    // name is "Statuses"
    
    
    1 person found this answer helpful.
    0 comments No comments

  2. Viorel 122.5K Reputation points
    2023-07-25T11:15:38.0133333+00:00

    Try this:

    MethodBase m = System.Reflection.MethodBase.GetCurrentMethod( );
    HttpGetAttribute a = m.GetCustomAttribute<HttpGetAttribute>( );
    string name = a.Template;
    

  3. AgaveJoe 1,510 Reputation points
    2023-07-25T13:05:19.7133333+00:00

    I'm anticipating "Statuses" as the method name.

    Statuses is an attribute route not a method name.

    Routing in ASP.NET Core

    Routing to controller actions in ASP.NET Core

    [HttpGet("Statuses")]
    

    It seems rather odd to fetch the route in the controller if the intent is to log the route. Middleware seems like a better approach.

    app.Use(async (context, next) =>
    {
        var url = context.Request.GetDisplayUrl();
        Microsoft.AspNetCore.Routing.RouteData route = context.GetRouteData();
        var endpoint = context.Features.Get<IEndpointFeature>().Endpoint;
    
        // Do work that can write to the Response.
        await next.Invoke();
        // Do logging or other work that doesn't write to the Response.
    });
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.