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 ?
How does routing work in ASP.NET Core MVC? In an empty project, update Startup class to add services and middleware for MVC. Add HomeController to demonstrate the conventional routing (see discussion). Add a controller named WorkController to demonstrate the attribute routing.
Conventional or Traditional Routing also is a pattern matching system for URL that maps incoming request to the particular controller and action method. We set all the routes in the RouteConfig file. RouteConfig file is available in the App_Start folder. We need to register all the routes to make them operational.
We can use Convention based Routing and Attribute Routing in the same project. Be sure attribute routing should be defined first to convention based routing.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With