Conventional default route in asp.net core not working

Viewed 3835

I can't seem to get my default route working in ASP.NET Core 2.0, am I overlooking something ?

Startup.cs

public class Startup
{
    public IConfiguration Configuration { get; set; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseMvc(routes => 
        {
            routes.MapRoute("default", "{controller}/{action}/{id?}", new { controller = "Home", action = "Index" });
        });
    }
}

HomeController.cs

[Route("[controller]")]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

when I browse to the URL, nothing happens, and it does not redirect to Home ?

2 Answers

Just remove the [Route("[controller]")] decoration on the controller.

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

With the default routing you registered in the UseMvc method with the conventional route patterns, now it should work for yourBaseUrl and yourBaseUrl\Home and yourBaseUrl\Home\Index

Typically you use the [Route("[controller]")] attribute on a controller level as a route prefix for all the routes on that controller to create custom attribute route definitions for your action methods.

[Route("[controller]")]
public class HomeController : Controller
{
    [Route("myseofriendlyurlslug")]
    public IActionResult Index()
    {
        return View();
    }
}

Now your action method will be accessible via yourBaseUrl/Home/myseofriendlyurlslug

Keep in mind that, when using attribute routing like above, the conventional routing pattern won't work.

this work fine

//Startup.cs

...

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

...

//HomeController.cs

...

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

....
Related