【问题标题】:How do I get MethodInfo of a controller action with HttpContext? (NET CORE 2.2)如何使用 HttpContext 获取控制器操作的 MethodInfo? (网络核心 2.2)
【发布时间】:2021-04-01 21:25:01
【问题描述】:

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

感谢您的宝贵时间。

【问题讨论】:

    标签: c# asp.net-core .net-core reflection methodinfo


    【解决方案1】:

    可以通过反射判断方法中是否包含AsyncStateMachineAttribute

    不知道你想怎么得到这个结果,这里有两种方法:

    第一种方式

    1.在任何地方创建方法:

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

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

    第二种方式

    1.自定义一个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.注册过滤器:

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

    参考:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-17
      • 2012-06-04
      • 2017-05-27
      • 2020-11-02
      • 1970-01-01
      相关资源
      最近更新 更多