在ASPNETCORE中獲得所有Action
本文旨在記錄自己在aspnetcore工作中需要獲取所有Action,在查詢了資料后進行了幾種方法的記錄。后期有發現其它方式再進行追加。
一、通過 反射 查看
(該方法過於常見,此處略)
二、通過 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;
}
}
方法優缺點:
- 優點:
使用方便;
能直接獲取所有注冊的Controller;
- 缺點:
不能獲取action信息;
不能方便的獲取路由信息;
三、通過 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;
}
方法優缺點
- 優點:
能快速查看所有的acton詳細信息及其路由信息,包括參數信息,特性等等;
- 缺點:
不能方便得查看Controller的信息;