问题描述
我知道我必须使用反射,但我不知道如何使用。 我试图从启动中间件了解 MethodInfo。 我需要 MethodInfo 来了解我正在调用的操作是否是异步的。
感谢您抽出宝贵时间。
解决方法
可以通过反射判断方法是否包含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>();
});
参考: