How to fix Using 'UseMvc' to configure MVC is not supported while using Endpoint Routing

By FoxLearn 6/10/2024 8:55:26 AM   506
How to solve the problem Using 'UseMvc' to configure MVC is not supported while using Endpoint Routing when changing ASP.NET Core 2.2 to 3.0

If you're encountering the error "Using 'UseMvc' to configure MVC is not supported while using Endpoint Routing," it means you're trying to use the old MVC configuration method (UseMvc) in an ASP.NET Core 3.0 or later application, which is not compatible with Endpoint Routing.

Warning MVC1005 Using 'UseMvc' to configure MVC is not supported while using Endpoint Routing. To continue using 'UseMvc', please set 'MvcOptions.EnableEndpointRouting = false' inside 'ConfigureServices'.

Here's how to resolve this issue.

Open your Startup class, If your code as shown below.

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

If you get an error as shown below when running your project.

'EndpointRoutingMiddleware matches endpoints setup by EndpointMiddleware and so must be added to the request execution pipeline before EndpointMiddleware. Please add EndpointRoutingMiddleware by calling 'IApplicationBuilder.UseRouting' inside the call to 'Configure(...)' in the application startup code.'

Remove the UseMvc method call from your Startup.cs file.

In your Startup.cs, make sure to enable Endpoint Routing by calling UseRouting() before UseEndpoints().

app.UseRouting();

ASP.NET Core 3.0 uses a refined endpoint routing which will generally give more control about routing within the application. Endpoint routing works in two separate steps:

In a first step, the requested route is matched again the configured routes to figure out what route is being accessed.

In a final step, the determined route is being evaluated and the respective middleware, e.g. MVC, is called.

These are two separate steps to allow other middlewares to act between those points. That allows those middlewares to utilize the information from endpoint routing, e.g. to handle authorization, without having to execute as part of the actual handler (e.g. MVC).

Finally, Ensure that all the necessary NuGet packages are updated to their ASP.NET Core 3.0 versions.