How do I get MethodInfo of a controller action with HttpContext? (NET CORE 2.2)

1.5k Views Asked by At

I know that I have to use reflection but I don't know how. I'm trying to know the MethodInfo from a StartUp Middleware. I need the MethodInfo to know if the action that I'm invoking is or is not async.

Thank you for your time.

1

There are 1 best solutions below

0
Rena On BEST ANSWER

You could use reflection to judge if the method contains AsyncStateMachineAttribute.

Not sure how do you want to get this result, here are two ways:

First way

1.Create the method in anywhere:

public bool IsAsyncMethod(Type classType, string methodName)
{
    // Obtain the method with the specified name.
    MethodInfo method = classType.GetMethod(methodName);

    Type attType = typeof(AsyncStateMachineAttribute);

    // Obtain the custom attribute for the method. 
    // The value returned contains the StateMachineType property. 
    // Null is returned if the attribute isn't present for the method. 
    var attrib = (AsyncStateMachineAttribute)method.GetCustomAttribute(attType);

    return (attrib != null);
}

2.Call the method in your controller:

[HttpGet]
public async Task<IActionResult> Index()
{
       var data= IsAsyncMethod(typeof(HomeController), "Index");
        return View();
}

Second way

1.Custom an ActionFilter and it will judge the method async or not before getting into the method:

using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Reflection;
using System.Runtime.CompilerServices;

public class CustomFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
     {

        var controllerType = context.Controller.GetType();      
        var actionName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ActionName;

        MethodInfo method = controllerType.GetMethod(actionName);

        Type attType = typeof(AsyncStateMachineAttribute);

        // Obtain the custom attribute for the method.
        // The value returned contains the StateMachineType property.
        // Null is returned if the attribute isn't present for the method.
        var attrib = (AsyncStateMachineAttribute)method.GetCustomAttribute(attType);

        //do your stuff....
    }
    public void OnActionExecuted(ActionExecutedContext context)
    {
        // Do something after the action executes.
    }
}

2.Register the filter:

services.AddMvc(
    config =>
    {
        config.Filters.Add<CustomFilter>();
    });

Reference:

https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.asyncstatemachineattribute?view=net-5.0