在ASP.NET MVC中创建自定义控制器工厂

时间:2014-04-25 10:05:39

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-controller controller-factory

我正在查看一本书中的示例,其中作者正在尝试创建自定义控制器工厂,如下所示。 (仅参考CreateController方法)

public IController CreateController(RequestContext requestContext,  
            string controllerName) { 

            Type targetType = null; 
            switch (controllerName) { 
                case "Product": 
                    targetType = typeof(ProductController); 
                    break; 
                case "Customer": 
                    targetType = typeof(CustomerController); 
                    break; 
                default: 
                    requestContext.RouteData.Values["controller"] = "Product"; 
                    targetType = typeof(ProductController); 
                    break; 
            } 

            return targetType == null ? null : 
                (IController)DependencyResolver.Current.GetService(targetType); 
        }

对于默认情况,controllerName默认情况的值将设置为现有控制器(Product)。给出的原因是这将导致MVC框架搜索与回退控制器相关联的视图而不是用户请求的控制器。 我的问题是为什么不以类似的方式搜索产品和客户的观点?

1 个答案:

答案 0 :(得分:0)

您现在将使用自定义控制器工厂。但默认视图引擎配置为在以下位置搜索。 (例如家庭控制器,索引操作)

~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml 

~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx

您可以编写自定义视图引擎并将其实施以搜索其他位置,并以此方式实现"后备"位置。

相关问题