在ASPNETCORE中得到全部Action
本文旨在記錄本身在aspnetcore工做中須要獲取全部Action,在查詢了資料後進行了幾種方法的記錄。後期有發現其它方式再進行追加。c#
1、經過 反射 查看
(該方法過於常見,此處略)app
2、經過 ApplicationPartManager 查看
- 經過構造函數注入
ApplicationPartManager
; - 經過
PopulateFeature()
方法將數據設置到ControllerFeature
實例中;
public class ListController : Controller { public ListController(ApplicationPartManager applicationPartManager) { _applicationPartManager = applicationPartManager; } private ApplicationPartManager _applicationPartManager; public IEnumerable<dynamic> List() { var controllerFeature = new ControllerFeature(); _applicationPartManager.PopulateFeature(controllerFeature); var data = controllerFeature.Controllers.Select(x => new { Namespace = x.Namespace, Controller = x.FullName, ModuleName = x.Module.Name, Actions = x.DeclaredMethods.Where(m=>m.IsPublic && !m.IsDefined(typeof(NonActionAttribute))).Select(y => new { Name = y.Name, ParameterCount = y.GetParameters().Length, Parameters = y.GetParameters() .Select(z => new { z.Name, z.ParameterType.FullName, z.Position, Attrs = z.CustomAttributes.Select(m => new { FullName = m.AttributeType.FullName, }) }) }), }); return data; } }
方法優缺點:ide
- 優勢:
使用方便; 能直接獲取全部註冊的Controller;函數
- 缺點:
不能獲取action信息; 不能方便的獲取路由信息;spa
3、經過 IActionDescriptorCollectionProvider 查看
- 經過構造函數注入
IActionDescriptorCollectionProvider
實例;
private IActionDescriptorCollectionProvider _actionProvider; public IEnumerable<dynamic> List() { var actionDescs = _actionProvider.ActionDescriptors.Items.Cast<ControllerActionDescriptor>().Select(x => new { ControllerName = x.ControllerName, ActionName = x.ActionName, DisplayName = x.DisplayName, RouteTemplate = x.AttributeRouteInfo.Template, Attributes = x.MethodInfo.CustomAttributes.Select(z=>new { TypeName = z.AttributeType.FullName, ConstructorArgs = z.ConstructorArguments.Select(v => new { ArgumentValue = v.Value }), NamedArguments = z.NamedArguments.Select(v => new { v.MemberName, TypedValue = v.TypedValue.Value, }), }), ActionId = x.Id, x.RouteValues, Parameters = x.Parameters.Select(z => new { z.Name, TypeName = z.ParameterType.Name, }) }); return actionDescs; }
方法優缺點code
- 優勢:
能快速查看全部的acton詳細信息及其路由信息,包括參數信息,特性等等;ip
- 缺點:
不能方便得查看Controller的信息;路由