如何通过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
相关产品推荐
相关产品推荐

