markmnl
markmnl

Reputation: 11326

Changing ASP Core default route to different controller

I cannnot get my ASP .NET Core MVC site to route to different controller other than Home. I changed the default route in Startup (it is the only route):

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

my ProfileController looks like:

public class ProfileController : Controller
{
    [HttpGet("index")]
    public IActionResult Index() 
    {
        return View();
    }
    ...
}

But all I get is 404 returned form the Kestrel server on navigating to base URL.

Upvotes: 0

Views: 3482

Answers (1)

Fabricio Koch
Fabricio Koch

Reputation: 1435

I've just created a new project and it worked for me. Maybe you're doing something else wrong.

Here's what I did.

  • Create a new asp.net core web application project (choose MVC template)
  • Update the default route in the Startup.cs:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
      loggerFactory.AddConsole(Configuration.GetSection("Logging"));
      loggerFactory.AddDebug();
    
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
      } else {
        app.UseExceptionHandler("/Home/Error");
      }
    
      app.UseStaticFiles();
    
      app.UseMvc(routes => {
        routes.MapRoute(
            name: "default",
            template: "{controller=profile}/{action=index}/{id?}");
      });
    }
    
  • Create the Profile Controller:

    public class ProfileController : Controller {
      // GET: /<controller>/
      public IActionResult Index() {
        return View();
      }
    }
    
  • Create the Index View for the Profile Controller:

enter image description here

  • Run the project and the Profile's Index page should open.

UPDATE:

The problem was the [HttpGet("index")] in the Profile Controller.

Upvotes: 1

Related Questions