如何使用 HttpContext 获取控制器操作的 MethodInfo? (净核心 2.2)

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

我知道我必须使用反射,但我不知道如何使用。 我试图从 StartUp 中间件中了解 MethodInfo。 我需要 MethodInfo 来了解我正在调用的操作是否是异步的。

感谢您的宝贵时间。

可以使用反射判断方法是否包含AsyncStateMachineAttribute.

不确定如何得到这个结果,这里有两种方法:

第一种方式

1.Create 任何地方的方法:

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 控制器中的方法:

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

第二种方式

1.Custom一个ActionFilter,在进入方法之前判断方法是否异步:

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 过滤器:

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

参考:

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