【问题标题】:.net core 3 , MVC , Using 'UseMvcWithDefaultRoute' to configure MVC is not supported while using Endpoint Routing.net core 3 , MVC , Using 'UseMvcWithDefaultRoute' to configure MVC is not supported while using Endpoint Routing
【发布时间】:2020-02-04 13:26:02
【问题描述】:

我正在尝试创建一个基于 ASP.NET Core 3 的简单项目。

ASP.NET Core 2.2 的 MVC 模板在启动类中有以下行:

app.UseMvcWithDefaultRoute();

此行在 ASP.NET Core 2.2 中完美运行,并且路由工作正常,但是在 ASP.NET Core 3.0 中它无法编译并显示以下错误

使用端点路由时不支持使用“UseMvcWithDefaultRoutee”配置 MVC。

问题是:“如何在 .net core 版本 3 中为 MVC 应用程序配置路由?”

【问题讨论】:

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


    【解决方案1】:

    我在以下官方文档“Migrate from ASP.NET Core 2.2 to 3.0”中找到了解决方案:

    三种方法:

    1. 禁用端点路由。
    (add in Startup.cs)
    
    services.AddMvc(option => option.EnableEndpointRouting = false)
    
    

    1. 将 UseMvc 或 UseSignalR 替换为 UseEndpoints。

    在我的例子中,结果是这样的

      public class Startup
    {
        
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
    
        
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
    
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCors();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
            });
            
        }
    }
    

    1. 使用 AddControllers() 和 UseEndpoints()
    public class Startup
    {
        
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }
    
        
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
    
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCors();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            
        }
    }
    

    【讨论】:

      【解决方案2】:

      这在 ASP.NET Core 3 中不存在,您可以看到 here 它只支持到 2.2。

      注册完整的MVC管道时需要切换到app.UseMvc();

      对于 API,您需要执行以下操作

      app.UseRouting();
      app.UseEndpoints(builder => builder.MapControllers());
      

      【讨论】:

      • 感谢您的帮助,尽管我已经找到了解决方案,但非常感谢您的帮助。
      【解决方案3】:

      端点路由在 ASP.NET core 3.1 中可用,如果你想为 Home 控制器和索引操作添加默认路由,你必须禁用端点路由,完整的概念理解请访问 https://yogeshdotnet.com/use-of-app-usemvcwithdefaultroute-in-asp-net-core-3-1/

      【讨论】:

        猜你喜欢
        • 2021-04-02
        • 1970-01-01
        • 2020-11-08
        • 1970-01-01
        • 2022-12-26
        • 1970-01-01
        • 1970-01-01
        • 2018-05-17
        • 2021-12-28
        相关资源
        最近更新 更多