c# Mono.Cecil IL方式 读MethodBody

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 GetDecryptRequestMetaInfoList()
        {
            var decryptRequestMetaInfoList = new List();
            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<(?[^,]+),(?[^>]+)>");
                    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

你可能感兴趣的:(c# Mono.Cecil IL方式 读MethodBody)