扩展MVC框架

时间:2014-08-18 10:03:08

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing

我有一个带有一些基本路线的MVC应用程序,并且可以动态注册路由(尽管),这是id。

我只是为路线提供了基本的MVC实现:

public class RouteConfig
{
    #region Methods

    /// <summary>
    ///     Registers the routes.
    /// </summary>
    /// <param name="routes">The <see cref="RouteCollection" /> to which the routes will be added.</param>
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    }

    #endregion
}

现在,我想要一些东西,以便将路由添加到应用程序中很容易,但是你无法通过上面的源代码来注册路由。

我正在考虑某个接口,并且RouteConfig类将搜索所有程序集以查找实现此接口的类,而不是执行在那里定义的逻辑来注册路由,但我确实感觉这不是&#39正确的做法。

我想要这样的事情:

创建一个定义注册路径的方法的接口:

public interface IMvcRouteExtender
{
    #region Methods

    /// <summary>
    ///     Register routes for the application.
    /// </summary>
    /// <param name="routes">The <see cref="RouteCollection"/> that contains all the required routes.</param>
    void RegisterRoutes(RouteCollection routes);

    #endregion
}

创建一个实现此接口的类来注册所需的路由

public class RouteConfig : IMvcRouteExtender
{
    #region IMvcRouteExtender

    /// <summary>
    ///     Registers the routes.
    /// </summary>
    /// <param name="routes">The <see cref="RouteCollection" /> to which the routes will be added.</param>
    public void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute("Default", "pensions/save-and-pension", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    }

    #endregion
}

但现在问题是,如何确保首先完成IgnoreRoute注册,然后调用此类然后注册其余路由?

这两个路线配置之间没有强大的参考?

有没有人遇到这样的事情并且愿意帮助我?

我想避免将RouteConfig紧密耦合到另一个程序集。

正如SOLID原则所述,系统必须是开放式的,但需要修改。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您可以轻松地在示例中编写代码:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    GlobalConfiguration.Configuration.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional });

    RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    RouteTable.Routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { 
            controller = "Home", 
            action = "Index", 
            id = UrlParameter.Optional });
}

所以你不要改变RouteConfig类中的代码。 当然,这不是最好的做法......

修改:更新问题的答案在此链接中:How to register routes that have been defined outside Global.asax

Edit2 请提供这些步骤,如果您想做任何SOLID可写的说明......;

  1. 在您的解决方案下,创建一个名为的新项目.net库 “CoreRoutes”
  2. 在那里实施路线......(只是抽象新课,让我们说 来自路线类的“CoreLibraryRoutes”。 )
  3. 启动应用程序 - “搜索和注册路由功能” 在核心应用程序中,如下面的链接,但关键是;像a一样定义它 继承自CoreLibraryRoutes类的类......这是一种方法 它没有性能错误等。
  4. 现在,你可以毫无损失地使用它......
  5. 我无法制作/提供源代码,因为您应该尝试了解更多信息... 但是,如果你无论做什么都不会成功;然后我可以为你写。

    祝你好运......

答案 1 :(得分:-1)

WebActivator可能就是您正在寻找的东西。这将允许您创建一个程序集,并在&amp;标记为在应用程序启动时运行以加载路由的方法。