엔드 포인트 라우팅을 사용하는 동안 'UseMvc'를 사용하여 MVC를 구성하는 것은 지원되지 않습니다.


120

Asp.Net 코어 2.2 프로젝트가있었습니다.

최근에 .net core 2.2에서 .net core 3.0 Preview 8로 버전을 변경했습니다.이 변경 후 다음 경고 메시지가 표시됩니다.

엔드 포인트 라우팅을 사용하는 동안 'UseMvc'를 사용하여 MVC를 구성하는 것은 지원되지 않습니다. 'UseMvc'를 계속 사용하려면 'ConfigureServices'에서 'MvcOptions.EnableEndpointRouting = false'를 설정하십시오.

EnableEndpointRoutingfalse 로 설정 하면 문제를 해결할 수 있지만 문제를 해결하는 올바른 방법과 엔드 포인트 라우팅에 UseMvc()기능이 필요하지 않은 이유를 알아야 합니다.


2
적절한 방법에 대해 :이 문서 docs.microsoft.com/en-us/aspnet/core/migration/… "가능한 경우 앱을 끝점 라우팅으로 마이그레이션"이라고 설명합니다.
— dvitel

답변:


23

그러나 나는 그것을 해결하는 적절한 방법이 무엇인지 알아야합니다

일반적으로 EnableEndpointRouting대신을 사용해야 하며을 활성화하는 세부 단계는 라우팅 시작 코드 업데이트를UseMvc 참조하십시오 . EnableEndpointRouting

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

의 경우 EndpointMiddleware 를 EnableEndpointRouting사용 하여 요청을 엔드 포인트 로 라우팅합니다.


123

다음 공식 문서 " Migrate from ASP.NET Core 2.2 to 3.0 " 에서 해결책을 찾았습니다 .

세 가지 접근 방식이 있습니다.

  1. 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. 엔드 포인트 라우팅을 비활성화합니다. 예외 메시지가 제안하고 문서의 다음 섹션에서 언급했듯이 엔드 포인트 라우팅없이 mvc 사용


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

2
이 asp.net 코어 3.0에서 작동하고 나는 쉽게 추가 웹 API를 사용할 수 있습니다
— 토니 동아

1
그것은 사용 (해당 페이지에) 권장 services.AddRazorPages();대신services.AddMvc();
— BurnsBA

1
첫 번째 mvc 튜토리얼 을 진행하고 core2.1에서 core3.0으로 업그레이드 하는 경우 좋은 솔루션 입니다. 이것은 내 문제를 즉시 해결했습니다. 감사합니다!
— Spencer Pollock

옵션 3은 맨손으로 페이지를 구축하는 데 큰 도움이되었습니다
— Vic

50

이것은 나를 위해 일했습니다 (추가 Startup.cs> ConfigureServices 메서드).

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

2
간단한 대답이지만 훌륭한 대답입니다!
— noobprogrammer

3

.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 메소드,

여기에 이미지 설명 입력

감사합니다


2

DotNet Core 3.1의 경우

아래에서 사용

파일 : Startup.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();
        });
    }

모든 서비스 구성 라인을 어떻게 처리합니까?
— Fanchi

0

ConfigureServices 메서드에서 :를 사용할 수 있습니다.

services.AddControllersWithViews();

그리고 구성 방법 :

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

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

-4

아래 코드 사용

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

이 코드가 문제를 해결하는 방법 을 설명하면 도움이 될 것 입니다.
— 로버트 컬럼비아

단순히 코드를 게시하는 것만으로는 충분하지 않습니다. 이 코드가 질문에 답변하는 내용 / 이유 / 방법을 설명해주세요.
— nurdyguy

이 상자에서 나오는 그들이 adter있는 그와 실제로 사용자에게 도움이 나던 바로 보일러 플레이트입니다
— 사이먼 가격
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.