当前位置: 首页 > 工具软件 > Cecil > 使用案例 >

c# Mono.Cecil IL方式 读MethodBody

长孙雅志
2023-12-01
using Kufen.Common.Definitions;
using Mono.Cecil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

namespace Kufen.WebApi.SwaggerHelp
{
    public class SwaggerModelHelp
    {
        public static List<SwaggerEncryptModelInfo> GetDecryptRequestMetaInfoList()
        {
            var decryptRequestMetaInfoList = new List<SwaggerEncryptModelInfo>();
            var path = typeof(SwaggerModelHelp).Assembly.Location;
            var assembly = AssemblyDefinition.ReadAssembly(path);
            var toInspect = assembly.MainModule
              .GetTypes()
              .SelectMany(t => t.Methods.Select(m => new { t, m }))
              .Where(x => x.m.HasBody);
            toInspect = toInspect.Where(
                x => x.t.Name.EndsWith("Controller") &&
                x.m.IsPublic == true &&
                x.m.Parameters.Any(m => m.ParameterType.Name == nameof(DecryptRequest))
            );
            foreach (var method in toInspect)
            {
                var containsEncryptRequestMethodBody = method.m.Body.Instructions.ToList().Where(m => m.ToString().Contains("EncryptRequestHandler")).FirstOrDefault();
                if (containsEncryptRequestMethodBody != null)
                {
                    var ilStr = containsEncryptRequestMethodBody.ToString();
                    var regMatchResult = Regex.Match(ilStr, "EncryptRequestHandler<(?<EncryptRequestModel>[^,]+),(?<EncryptResponseModel>[^>]+)>");
                    var encryptRequestModel = regMatchResult.Groups["EncryptRequestModel"].Value;
                    var encryptResponseModel = regMatchResult.Groups["EncryptResponseModel"].Value;
                    decryptRequestMetaInfoList.Add(new SwaggerEncryptModelInfo
                    {
                        Controller = method.t.FullName,
                        Action = method.m.Name,
                        ReqModelType = encryptRequestModel,
                        ResModelType = encryptResponseModel
                    });
                }
            }
            return decryptRequestMetaInfoList;
        }
    }
}

 

转载于:https://www.cnblogs.com/gaocong/p/11532214.html

 类似资料: