首页 > 解决方案 > .net core 3 , MVC , Using 'UseMvcWithDefaultRoute' to configure MVC is not supported while using Endpoint Routing

问题描述

我正在尝试创建一个基于 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#.netasp.net-mvcasp.net-core

解决方案


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

有3种方法:

  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();
        });
        
    }
}

推荐阅读