【问题标题】:How to migrate routes from .NET to ASP.NET Core? (Specific example)如何将路由从 .NET 迁移到 ASP.NET Core? (具体例子)
【发布时间】:2016-08-17 13:52:43
【问题描述】:

我正在从 .NET 和 .NET Core 迁移,但在 startup.cs 中的路由配置有困难。

在 ASP.NET 项目中,我们有以下路由代码:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

现在,我正在尝试寻找可以简单地替换此功能的东西。到目前为止,我一直在做以下工作:

        app.UseMvc(routes =>
        {
        routes.MapRoute(
            name: "Default",
            template: "{controller}/{action}/{id?}",
            defaults: new { controller = "GHS", action = "RequestForm" });
        });

这适用于单个控制器和动作,但我正在寻找可以“RegisterAllAreas”的东西。

我从 Microsoft 找到了以下文章,但找不到与此特别匹配的任何内容。 https://docs.asp.net/en/latest/fundamentals/routing.html

有没有办法像在 .NET 代码中那样映射所有路由?

额外信息:

我认为在以前的版本中,url 是从 View 生成的,因为只有以下 url 有效:

http://localhost:23046/contact-us.html

http://localhost:23046/ghs-request.html

更新:

我刚刚意识到我的项目有两个名为“contact-us.html”和“ghs-request.html”的文件,这些 html 文件与 javascript 文件有关联。因此,我只需要将我的 View 表单连接到这些 html 脚本。

【问题讨论】:

  • 我正在尝试修改这个问题,因为我意识到这是一个愚蠢的问题。请让我知道我的错误,我会尝试修改它。

标签: c# asp.net .net asp.net-mvc asp.net-core


【解决方案1】:

试试这个

    app.UseMvc(routes =>
    {
        // areas
        routes.MapRoute(
            name: "area",
            template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

        // default
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

【讨论】:

    【解决方案2】:

    在最小 Program.cs 中的 .net 6 中,如果您使用所选答案给出的 UseMvc,您将收到警告:

    Warning MVC1005 Using 'UseMvc' to configure MVC is not supported while using Endpoint Routing. To continue using 'UseMvc', please set 'MvcOptions.EnableEndpointRouting = false' inside '<Main>$'.

    在 .net 6 中使用 .net 最小 Program.cs。 如果GHS 是您的控制器,RequestForm 是您的操作。

    app.MapControllerRoute(name: "default",
        pattern: "{controller=GHS}/{action=RequestForm}/{id?}"
        defaults: new { controller = "GHS", action = "RequestForm" });
    

    或者更简单的也应该可以工作

    app.MapControllerRoute(name: "default",
        defaults: new { controller = "GHS", action = "RequestForm" });
    

    app.MapControllerRoute(name: "default",
        pattern: "{controller=GHS}/{action=RequestForm}/{id?}");
    

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 2015-03-04
      • 2023-04-10
      • 1970-01-01
      • 2020-06-05
      • 2017-07-21
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多