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



我知道我必须使用反射,但我不知道如何使用。我正试图从一个StartUp中间件中了解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>();
});

参考:

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

最新更新