簡體   English   中英

如何使用 HttpContext 獲取 controller 操作的 MethodInfo? (網絡核心 2.2)

[英]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>();
    });

參考:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM