Controller in separate assembly and routing

前端 未结 2 998
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 12:44

In the same solution, there is a ASP.NET MVC4 application Slick.App and class library Awesome.Mvc.Lib. Awesome.Mvc.Lib contains one controller clas

相关标签:
2条回答
  • 2020-12-13 13:21

    The namespaces list on the route only gives priority to certain namespaces over the others, which are not listed :

    new [] {"Namespace1", "Namespace2"}
    

    doesn't give higher priority to Namespace1 as one would expect but just gives priority to both namespaces over the others.

    This means that the namespaces in the list are first searched for controllers and then, if no match is found the rest of the available controllers with that name are used.

    You can suppress the use of non prioritized controllers by doing this:

    var myRoute  = routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new [] { "Slick.App.Controllers" }
        );
    
    myRoute.DataTokens["UseNamespaceFallback"] = false;
    
    0 讨论(0)
  • 2020-12-13 13:22

    You can inherit from DefaultControllerFactory like this:

    public class CustomControllerFactory : DefaultControllerFactory
    {
        protected override Type GetControllerType(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            var type = base.GetControllerType(requestContext, controllerName);
    
            if (type != null && IsIngored(type))
            {
                return null;
            }
    
            return type;
        }
    
        public static bool IsIngored(Type type)
        {
            return type.Assembly.GetCustomAttributes(typeof(IgnoreAssemblyAttribute), false).Any() 
                || type.GetCustomAttributes(typeof(IgnoreControllerAttribute), false).Any();
        }
    }
    

    Then some changes to Global.asax

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
    
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
    
            ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());
        }
    

    And here you are! Any type marked with IgnoreControllerAttribute won't be visible. You can even hide the whole assembly.

    If you need some configuration based behaviour, it is not a great matter to make all necessary changes ;)

    0 讨论(0)
提交回复
热议问题