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

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

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

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

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



답변

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

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

Endpoint Routing에 UseMvc () 함수가 필요하지 않은 이유.

를 들어 UseMvc, 그것은 사용 the IRouter-based logicEnableEndpointRouting사용 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());
}

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


답변

다음 공식 문서 ” 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);


답변

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

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


답변

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

여기에 이미지 설명 입력

감사합니다


답변

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


답변

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

services.AddControllersWithViews();

그리고 구성 방법 :

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


답변

이것은 .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();
    });
}