Johnny
Johnny

Reputation: 869

Dot.NET Core 5 Routing

I am trying to route to a page, but it is not working as I anticipated.

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

            endpoints.MapControllerRoute("onwhite", 
                               "{ controller=Portfolio}/{action=OnWhite}");
        });

I can get to the Default index page just fine, utilizing the root Domain, however if I try to visit https://www.example.com/onwhite, it fails to locate the page. Consequently, calling https://www.example.com/Portfolio/OnWhite also works just fine.

How do I get what I am looking for in .NET Core 5 if I use the Routing Endpoints?

Upvotes: 0

Views: 253

Answers (1)

bfren
bfren

Reputation: 493

Controller endpoint mapping needs to be done in order of most specific to least specific.

What's happening here is that the first ('default') route is being matched, and .NET is looking for a class called 'OnwhiteController' - which doesn't exist. It's not even reaching the 'onwhite' route definition.

What you need is to define a custom pattern - 'onwhite' - and specify which controller and action need to be used to display that page.

app.UseRouting();
app.UseEndpoints(endpoints =>
{
     endpoints.MapControllerRoute(
         name: "onwhite", 
         pattern: "onwhite", // this is what matches in the URL
         defaults: new { controller = "Portfolio", action = "OnWhite" }
     );

     endpoints.MapControllerRoute("default",
         "{controller=Home}/{action=Index}/{id?}");
});

Separating routes

The UseEndpoints method here takes a single parameter Action<IEndpointRouteBuilder>. You could create a static class to hold all your routes like this, which would help keep your Startup.cs file clean:

public static class Endpoints
{
    public static void Add(IEndpointRouteBuilder endpoints)
    {
        endpoints.MapControllerRoute(
            name: "onwhite", 
            pattern: "onwhite", // this is what matches in the URL
            defaults: new { controller = "Portfolio", action = "OnWhite" }
        );

        // add the rest of your endpoints here

        endpoints.MapControllerRoute("default",
            "{controller=Home}/{action=Index}/{id?}");
    }
}

And then you can do this in ConfigureServices:

app.UseEndpoints(Endpoints.Add);

Upvotes: 1

Related Questions