![](/img/trans.png)
[英]Having an HttpContext how can I get the "MethodInfo" of the action that is going to be executed?
[英]How do I get MethodInfo of a controller action with HttpContext? (NET CORE 2.2)
我知道我必須使用反射,但我不知道如何。 我正在嘗試從 StartUp Middleware 中了解 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.調用controller中的方法:
[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>();
});
參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.