.net 有了HttpContext,我如何才能获得将要执行的操作的“MethodInfo”?

amrnrhlw  于 2022-11-19  发布在  .NET
关注(0)|答案(1)|浏览(149)

下面的代码:

[LayoutRenderer("http-request")]
    public class NLogHttpRequestLayoutRenderer : AspNetRequestPostedBody
    {     
        protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
        {
            base.DoAppend(builder, logEvent);
            var body = builder.ToString();
            
           // after getting the type of the action's request model do serialization deserialization things ...
          
        }

这是我的nLog渲染器。它会将每个请求主体渲染到日志系统中。但有些主体包含敏感数据,如电子邮件或银行卡。我想屏蔽这些数据。为此,我需要了解操作请求的类型。考虑到这一点,我有以下操作:

[HttpPost]
        [Route("api/v1/payment/pay")]
        [MaskRequestMethod(typeof(PaymentRequest))]
        public Task<BankCardActionResponse> Pay([FromBody] PaymentRequest request)
        {
            if (request == null)
                throw new HttpResponseException(HttpStatusCode.BadRequest);

            return _paymentService.PayAsync(SsoHelper.Ctn, request);
        }

问题是,如果我有HttpContext,我如何才能进入渲染器的MethodInfo动作。因为如果我得到MethodInfo,我可以检索属性[MaskRequestMethod(typeof(PaymentRequest))],并从属性中得到Type。有了Type,我可以反序列化JSON主体,根据预先编程的规则屏蔽它,然后再次序列化它。这就是我为什么需要它的简短解释。
于是,问题来了:如果我有HttpContext,我能得到将要执行的操作的MethodInfo吗?

q3qa4bjr

q3qa4bjr1#

您可以使用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.
    }
}

相关问题