在 asp.net mvc 中是否可以制作通用控制器? [英] In asp.net mvc is it possible to make a generic controller?

查看:22
本文介绍了在 asp.net mvc 中是否可以制作通用控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个通用控制器,即:

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.

您希望 /Product/Index 触发 MyController.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆