Home > Net >  ASP.NET Core: UsePathBase extracts pathbase from path but MapControllers() does not consider path
ASP.NET Core: UsePathBase extracts pathbase from path but MapControllers() does not consider path

Time:12-22

I used UsePathBase in a dotnet 2.1 application.

app.UsePathBase("/app1"); // extract /app1 from path 
app.UseMvc(routers => ...) // routes consider path only

This does no longer work in dotnet 6: When i use

app.UsePathBase("/app1");
app.MapControllers(); // controller routing does not consider the reduced path

While before

"/app1/home/index" routed to HomeController, Index method

this now fails to route anywhere.

Am I doing something wrong?

I diagnosed with

app.Use((context, next) =>
{
    Console.WriteLine("=> {0}", context);
    return next.Invoke();
});

which shows that UsePathBase works, its the later routing in MapControllers that does not work. At least that is what I get out of that observation.

CodePudding user response:

Add explicit call to UseRouting after UsePathBase:

app.UsePathBase("/app1");
app.UseRouting();
app.MapControllers(); 

Read more.

P.S.

Was not able to repro in .NET 7 solution, only in .NET 6 one, maybe it was fixed/reverted.

CodePudding user response:

In .NET 6, the UsePathBase middleware has been replaced with the UseRouting middleware.

The UseRouting middleware is responsible for both routing and path base handling.

to set a pathbase in .NET 6, you may try something like this:

app.UseRouting(routes =>
{
    routes.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}",
        defaults: new { controller = "Home", action = "Index" },
        constraints: new { id = new IntRouteConstraint() },
        dataTokens: new { pathBase = "/app1" }
    );
});
  • Related