在asp.net mvc的是有可能使通用控制器? [英] In asp.net mvc is it possible to make a generic controller?
问题描述
我试图创建一个通用的控制器,例如:
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'
所以,我的问题,是有可能使通用控制器asp.net的MVC?
So, my question, Is it possible to make a generic controller in asp.net mvc?
谢谢!
推荐答案
如果我理解你正确,你正在尝试做的,是借道类型T的通用控制器,一个给定的模型的所有请求。
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.
您会喜欢T的基础上要求模型有所不同。
You would like the T to vary based on the Model requested.
您想 /产品/指数
引发 myController的&LT;产品&GT;的.index()
这可以通过编写完成自己的 IControllerFactory
和实施 CreateController
的方法是这样的:
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屋!