在MVC5中,我有自己的VirtualPathProviderViewEngine
,并有以下内容:
string controllerAssemblyName = controllerContext.Controller.GetType().Assembly.FullName;
我用它来动态添加视图位置。
无论如何,我正在迁移到.NET Core并编写自己的IViewLocationExpander
,并且需要确定那里的控制器类型以执行相同的操作。方法签名如下:
public virtual IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
我所拥有的只是ViewLocationExpanderContext
的一个实例,它只提供ControllerName
和AreaName
属性,但没有实际的Controller实例。有没有办法使用这两个属性获取控件的实例或至少完整的类型名称?
我也尝试了以下内容:
var controllerContext = new ControllerContext(context.ActionContext);`
这给了我一个ControllerContext
的实例,但与MVC5不同,它上面没有Controller
属性。
答案 0 :(得分:1)
感谢@Nkosi。我已经使用了他的答案,我的解决方案如下。我不确定CreateControllerFactory()
部分是否良好,但如果controllerActionDescriptor
为NULL,则为我的后备:
string controllerAssemblyName = null;
var controllerActionDescriptor = context.ActionContext.ActionDescriptor as ControllerActionDescriptor;
if (controllerActionDescriptor != null)
{
var controllerTypeInfo = controllerActionDescriptor.ControllerTypeInfo;
controllerAssemblyName = controllerTypeInfo.AsType().Assembly.FullName;
}
else
{
var controllerContext = new ControllerContext(context.ActionContext);
var factory = CreateControllerFactory();
var controller = factory.CreateController(controllerContext);
controllerAssemblyName = controller.GetType().Assembly.FullName;
}
private static DefaultControllerFactory CreateControllerFactory()
{
var propertyActivators = new IControllerPropertyActivator[]
{
new DefaultControllerPropertyActivator(),
};
return new DefaultControllerFactory(
new DefaultControllerActivator(new TypeActivatorCache()),
propertyActivators);
}
答案 1 :(得分:0)
检查ActionContext
以访问所需信息。
应该能够深入到上下文中以获取动作控制器类型信息和程序集全名
public virtual IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) {
var controllerActionDescriptor = context.ActionContext.ActionDescriptor as ControllerActionDescriptor;
if(controllerActionDescriptor != null) {
var controllerTypeInfo = controllerActionDescriptor.ControllerTypeInfo;
//From the type info you should be able to get the assembly
var controllerAssemblyName = controllerTypeInfo.AsType().Assembly.FullName.ToString();
}
//...
}