DomBurf
DomBurf

Reputation: 2522

ASP.NET Core 3.0 not routing correctly

I have recently upgraded an existing ASP.NET Core 2.2 web app to 3.0. Everything now compiles. However when I go to run the application I am greeted with a directory listing instead of the login page.

enter image description here

Our app uses Razor pages as opposed to full blown MVC. Reading around the many changes in ASP.NET Core 3.0 I can see that the way in which routing is implemented has changed substantially.

Previously in the ConfigureServices we had the following.

services.AddMvc()
                .AddRazorPagesOptions(options => { options.Conventions.AuthorizeFolder("/"); });

And in the Configure method we had this.

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

This all worked fine. What changes are needed to get the app to route correctly now that we have upgraded to ASP.NET Core 3.0.

Upvotes: 0

Views: 666

Answers (2)

Husam Ebish
Husam Ebish

Reputation: 6768

In .Net Core 3 & .Net Core 3.1 you have to delete services.AddMvc().AddRazorPagesOptions(options => { options.Conventions.AuthorizeFolder("/"); }); and services.AddMvc(); from ConfigureServices:

Then add services.AddRazorPages();

In Configure add:

app.UseRouting();

app.UseEndpoints(endpoints => endpoints.MapRazorPages());

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

Finally your code will be like this:

  public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
            {
                services.AddRazorPages();
            }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                app.UseRouting();
                app.UseEndpoints(endpoints => endpoints.MapRazorPages());
                app.UseEndpoints(endpoints =>
                                             {
                                               endpoints.MapControllerRoute("default", " 
                                               {controller=Home}/{action=Index}/{id?}");
                                              });                 
            }
    }

To get more information take a look at Microsof documentation

Upvotes: 2

Felipe Oriani
Felipe Oriani

Reputation: 38598

You have to define the default controller on the default route. For sample:

app.UseMvc(routes =>
           {
               routes.MapRoute(
                   name: "default",
                   template: "{controller=Home}/{action=Index}/{id?}");
           });

I am not sure if your default controller should be Home but define it on the template and it will work when the user with an empty route access the applicaton.

Upvotes: 1

Related Questions