You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过HttpContext获取待执行Action的MethodInfo?

通过HttpContext获取目标Action的MethodInfo

ASP.NET Web API(非Core版本)

从HttpContext中拿到当前请求的HttpRequestMessage,再通过路由数据获取Action描述符,最终提取MethodInfo:

var request = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage;
if (request != null)
{
    var actionDescriptor = request.GetRouteData().GetActionDescriptor();
    MethodInfo targetMethod = actionDescriptor.MethodInfo;
    
    // 提取自定义的MaskRequestMethod属性
    var maskAttribute = targetMethod.GetCustomAttribute<MaskRequestMethodAttribute>();
    if (maskAttribute != null)
    {
        Type requestModelType = maskAttribute.RequestType; // 对应你属性里的请求模型类型
        // 后续反序列化、脱敏逻辑
    }
}

ASP.NET Core版本

通过HttpContext.GetEndpoint()获取端点元数据,从中提取ControllerActionDescriptor来拿到MethodInfo:

var endpoint = HttpContext.GetEndpoint();
if (endpoint != null)
{
    var actionDescriptor = endpoint.Metadata.GetMetadata<ControllerActionDescriptor>();
    if (actionDescriptor != null)
    {
        MethodInfo targetMethod = actionDescriptor.MethodInfo;
        
        var maskAttribute = targetMethod.GetCustomAttribute<MaskRequestMethodAttribute>();
        if (maskAttribute != null)
        {
            Type requestModelType = maskAttribute.RequestType;
            // 执行脱敏操作
        }
    }
}

关键注意点

  • 要确保代码执行时机在路由匹配完成之后,否则HttpContext中不会包含Action的元数据。
  • 你的MaskRequestMethodAttribute需要标记[AttributeUsage(AttributeTargets.Method)],确保能被GetCustomAttribute正确识别。

内容的提问来源于stack exchange,提问作者Aleksej_Shherbak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:55:21