Setup a default route in ASP.NET Core 3.1 MVC

1 minute read

ASP.NET Core

Creating a new ASP.NET Core Web Application on choosing an empty template will leave you with the empty configuration in the startup class file. The default route has to be set up in the startup class file.

The below code will demonstrate on setting up the default route in startup class file,

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
  }

  app.UseRouting();

  // You can enable the below commented code to print the "Hello world!" string instead of taking the user to MVC view
  //app.UseEndpoints(endpoints = {
    // endpoints.MapGet("/", async context = {
      // await context.Response.WriteAsync("Hello World!");
    // }
  // });

  // This will configure the default route in the app builder
  app.UseEndpoints(endpoints = {
    endpoints.MapControllerRoute(
      name: "default",
      pattern: "{controller=home}/{action=Index}"
    );
  });
}

home/index - is your default controller/index name.

You can launch your website now and it will take you to the default index page of the home controller.

Leave a comment