使用端点路由时,不支持使用“ UseMvc”来配置MVC

时间:2019-08-28 01:48:09

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

我有一个Asp.Net core 2.2项目。

最近,我将版本从.net core 2.2更改为.net core 3.0 Preview8。更改之后,我看到以下警告消息:

  

使用Endpoint时不支持使用'UseMvc'配置MVC   路由。要继续使用“ UseMvc”,请设置   在“ ConfigureServices”内部为“ MvcOptions.EnableEndpointRouting = false”。

我了解到,通过将EnableEndpointRouting设置为false可以解决此问题,但是我需要知道什么是解决该问题的正确方法,以及为什么端点路由不需要UseMvc()功能。

11 个答案:

答案 0 :(得分:31)

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

有3种方法:

  
      
  1. 用UseEndpoints替换UseMvc或UseSignalR。
  2.   

就我而言,结果看起来像这样

  public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {
        //Old Way
        services.AddMvc();
        // New Ways
        //services.AddRazorPages();
    }


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

    }
}

OR

  
      
  1. 使用AddControllers()和UseEndpoints()
  2.   
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();
        });

    }
}

OR

  
      
  1. 禁用端点路由。正如异常消息所建议的那样,并在文档的以下部分中提到:use mvcwithout endpoint routing
  2.   

services.AddMvc(options => options.EnableEndpointRouting = false);
//OR
services.AddControllers(options => options.EnableEndpointRouting = false);

答案 1 :(得分:10)

这对我有用(添加到Startup.cs中)

services.AddMvc(option => option.EnableEndpointRouting = false)

答案 2 :(得分:9)

  

但是我需要知道什么是解决该问题的正确方法

通常,您应该使用EnableEndpointRouting而不是UseMvc,并且可以参考Update routing startup code来启用EnableEndpointRouting的详细步骤。

  

为什么端点路由不需要UseMvc()函数。

对于UseMvc,它使用the IRouter-based logic,而EnableEndpointRouting使用endpoint-based logic。它们遵循以下不同的逻辑:

if (options.Value.EnableEndpointRouting)
{
    var mvcEndpointDataSource = app.ApplicationServices
        .GetRequiredService<IEnumerable<EndpointDataSource>>()
        .OfType<MvcEndpointDataSource>()
        .First();
    var parameterPolicyFactory = app.ApplicationServices
        .GetRequiredService<ParameterPolicyFactory>();

    var endpointRouteBuilder = new EndpointRouteBuilder(app);

    configureRoutes(endpointRouteBuilder);

    foreach (var router in endpointRouteBuilder.Routes)
    {
        // Only accept Microsoft.AspNetCore.Routing.Route when converting to endpoint
        // Sub-types could have additional customization that we can't knowingly convert
        if (router is Route route && router.GetType() == typeof(Route))
        {
            var endpointInfo = new MvcEndpointInfo(
                route.Name,
                route.RouteTemplate,
                route.Defaults,
                route.Constraints.ToDictionary(kvp => kvp.Key, kvp => (object)kvp.Value),
                route.DataTokens,
                parameterPolicyFactory);

            mvcEndpointDataSource.ConventionalEndpointInfos.Add(endpointInfo);
        }
        else
        {
            throw new InvalidOperationException($"Cannot use '{router.GetType().FullName}' with Endpoint Routing.");
        }
    }

    if (!app.Properties.TryGetValue(EndpointRoutingRegisteredKey, out _))
    {
        // Matching middleware has not been registered yet
        // For back-compat register middleware so an endpoint is matched and then immediately used
        app.UseEndpointRouting();
    }

    return app.UseEndpoint();
}
else
{
    var routes = new RouteBuilder(app)
    {
        DefaultHandler = app.ApplicationServices.GetRequiredService<MvcRouteHandler>(),
    };

    configureRoutes(routes);

    routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(app.ApplicationServices));

    return app.UseRouter(routes.Build());
}

对于EnableEndpointRouting,它使用EndpointMiddleware将请求路由到端点。

答案 3 :(得分:6)

我发现的问题归因于.NET Core框架的更新。最新的.NET Core 3.0发布版本要求使用MVC的明确加入。

当尝试从较早的.NET Core(2.2或预览版3.0版)迁移到.NET Core 3.0时,此问题最明显

如果从2.2迁移到3.0,请使用以下代码解决该问题。

expired

如果使用.NET Core 3.0模板,

services.AddMvc(options => options.EnableEndpointRouting = false);
修复后的

ConfigServices方法,

enter image description here

谢谢

答案 4 :(得分:3)

对于DotNet Core 3.1

在下面使用

文件:Startup.cs 公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment env) {

SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/###/edit#gid=0")

答案 5 :(得分:2)

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        //Old Way
        services.AddMvc();
        // New Ways
        //services.AddRazorPages();
    }

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

这也适用于 .Net Core 5

答案 6 :(得分:1)

您可以使用: 在ConfigureServices方法中:

services.AddControllersWithViews();

对于配置方法:

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

答案 7 :(得分:1)

在 ASP.NET 5.0 上默认禁用端点路由

只需像启动时一样配置

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options => options.EnableEndpointRouting = false);
    }
    

这对我有用

答案 8 :(得分:0)

这在.Net Core 3.1上对我有用。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

答案 9 :(得分:0)

这对我有用

 services.AddMvc(options => options.EnableEndpointRouting = false); or 
 OR
 services.AddControllers(options => options.EnableEndpointRouting = false);

答案 10 :(得分:-3)

使用以下代码

app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });