ChatGPT解决这个技术问题 Extra ChatGPT

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

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

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

使用端点路由时不支持使用“UseMvc”配置 MVC。要继续使用“UseMvc”,请在“ConfigureServices”中设置“MvcOptions.EnableEndpointRouting = false”。

我知道通过将 EnableEndpointRouting 设置为 false 可以解决问题,但我需要知道解决问题的正确方法是什么以及为什么 Endpoint Routing 不需要 UseMvc() 功能。

关于正确方法:此文档 docs.microsoft.com/en-us/aspnet/core/migration/… 声明“如果可能,将应用程序迁移到端点路由”

S
Sergii Zhuravskyi

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

有3种方法:

将 UseMvc 或 UseSignalR 替换为 UseEndpoints。

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

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

    }
}

或 2. 使用 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();
        });

    }
}

或 3. 禁用端点路由。正如异常消息所暗示的以及文档的以下部分中所提到的:使用 mvcwithout endpoint routing


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

这适用于 asp.net core 3.0,我可以轻松使用这个添加 Web API
建议(在该页面上)使用 services.AddRazorPages(); 而不是 services.AddMvc();
如果您要通过 first mvc tutorial 并从 core2.1 升级到 core3.0,这是一个很好的解决方案。这立即解决了我的问题,谢谢!
选项 3 非常适合我构建一个简单的页面
所以他们基本上只是将语法从 UseMvc() 稍微更改为 UseEndpoints()。
A
Arsen Khachaturyan

这对我有用(添加 Startup.cs > ConfigureServices 方法):

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

简单的答案,但很好的答案!
E
Edward

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

一般来说,您应该使用 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 将请求路由到端点。


A
Akash Limbani

我发现这个问题是由于 .NET Core 框架的更新造成的。最新的 .NET Core 3.0 发布版本需要明确选择加入才能使用 MVC。

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

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

services.AddMvc(options => options.EnableEndpointRouting = false);

如果使用 .NET Core 3.0 模板,

services.AddControllers(options => options.EnableEndpointRouting = false);

修复后的 ConfigServices 方法如下,

https://i.stack.imgur.com/fxbYL.png

谢谢你


M
Md. Nazmul Nadim

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

只需像启动一样配置

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

这对我有用


U
Unheilig

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

services.AddControllersWithViews();

对于配置方法:

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

这对我来说效果很好,但我需要添加 app.UseRouting();
R
Ramil Aliyev
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


C
Ciarán Bruen

对于 DotNet 核心 3.1

下面使用

文件:启动.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{         

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
       
    app.UseHttpsRedirection();
    app.UseRouting();
    app.UseAuthentication();
    app.UseHttpsRedirection();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

如何处理所有服务配置行?
r
rohit.khurmi095

-> 在 ConfigureServices 方法中 - Startup.cs

        //*****REGISTER Routing Service*****
        services.AddMvc();
        services.AddControllers(options => options.EnableEndpointRouting = false);

-> 在配置方法中 - Startup.cs

       //*****USE Routing***** 
        app.UseMvc(Route =>{
            Route.MapRoute(
                name:"default",
                template: "{Controller=Name}/{action=Name}/{id?}"
            );
        });

u
user9552541

这对我有用

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

M
Mandy

使用下面的代码

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

如果您解释了此代码如何解决问题,将会有所帮助。
仅仅发布代码是不够的。请解释此代码将回答问题的内容/原因/方式。
这只是开箱即用的样板,实际上并不能帮助用户了解他们的身份

关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅