在asp.net mvc是否有可能做一个通用控制器? [英] In asp.net mvc is it possible to make a generic controller?
问题描述
我试图创建一个通用控制器,例如:
public class MyController< T& :控制器其中T:SomeType
{...}
使用它,我遇到这个错误无处不在...
控制器名称必须以Controller结尾
这样,我的问题,是否可以在asp.net mvc中创建一个通用控制器?
谢谢!
如果我正确理解你,你想做的是通过一个类型T的通用控制器路由给定模型的所有请求。
您希望 / Product / Index
MyController< Product> .Index()
自己 IControllerFactory
并实现 CreateController
方法:
public IController CreateController(RequestContext requestContext,string controllerName)
{
Type controllerType = Type.GetType(MyController)
.MakeGenericType(Type.GetType (controllerName));
return Activator.CreateInstance(controllerType)as IController;
}
I'm attempting to create a generic controller, ie:
public class MyController<T> : Controller where T : SomeType
{ ... }
However, when I try to use it, I'm running into this error everywhere...
Controller name must end in 'Controller'
So, my question, Is it possible to make a generic controller in asp.net mvc?
Thanks!
If I understand you properly, what you are trying to do, is route all requests for a given Model through a generic controller of type T.
You would like the T to vary based on the Model requested.
You would like /Product/Index
to trigger MyController<Product>.Index()
This can be accomplished by writing your own IControllerFactory
and implementing the CreateController
method like this:
public IController CreateController(RequestContext requestContext, string controllerName)
{
Type controllerType = Type.GetType("MyController")
.MakeGenericType(Type.GetType(controllerName));
return Activator.CreateInstance(controllerType) as IController;
}
这篇关于在asp.net mvc是否有可能做一个通用控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!