我有一个具有如下语法的Controller:
public class CrudController<TEntity> : Controller
现在,如果我需要实体CrudController User,我只需要像这样扩展CrudController
UserCrudController : CrudController<User>
它运转得很好。但是,问题是,UserCrudController只是空的。另外,还有一些其他的CrudControllers也是空的。
现在,我正在寻找一种避免编写空crud控制器的方法。我只想用适当的泛型参数创建CrudController实例。也许是严格的命名约定,如下面所述。
@Html.ActionLink("Create", "UserCrud")
UserCrud (默认值)的控制器
UserCrud,将创建Crud<User> .现在,我可以做我想做的事了。但我该在哪做这些呢?在mvc中解析的url在哪里?
发布于 2012-06-21 04:56:49
在Craig对这个问题和this问题的评论及其公认的答案的帮助下,我已经解决了我的问题。
我已经实现了一个定制的CotrollerFactory
public class CrudControllerFactory : DefaultControllerFactory {
protected override Type GetControllerType(System.Web.Routing.RequestContext requestContext, string controllerName) {
Type controllerType = base.GetControllerType(requestContext, controllerName);
if(controllerType == null) {
int indexOfEntityEnd = controllerName.LastIndexOf("Crud");
if(indexOfEntityEnd >= 0) {
string entityName = controllerName.Substring(0, controllerName.Length - indexOfEntityEnd - 1);
// Get type of the CrudController and set to controller tye
}
}
return controllerType;
}
}然后在Application_Start()中,我添加了这一行:
ControllerBuilder.Current.SetControllerFactory(typeof(CrudControllerFactory));
https://stackoverflow.com/questions/11131215
复制相似问题