Setting default route in C# MVC

Viewed 802

I am creating a project in C# MVC and was using actions. Due to the requirements, now I am using Route to hide the controller name and display just the page name.

route config

 routes.MapMvcAttributeRoutes();
            routes.MapRoute(
                name: "Law",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Law", action = "Home", id = UrlParameter.Optional }
            );

controller 1 (to access this : http://localhost:17920/dashboard) and (http://localhost:17920/alert)

    public class LawController : Controller
    {
        [Route("dashboard")]
        [ActionName("Home")]
        public ActionResult Home()
        {
            return View();
        }
        
        [Route("alert")]
        [ActionName("alert-list")]
        public ActionResult AlertList()
        {
            return View();
        }

controller 2 (to access this : http://localhost:17920/list)

    public class ListController : Controller
    {
        [Route("list")]
        [ActionName("list-of-return")]
        public ActionResult listOfReturn()
        {
            return View();
        }

What I am trying is when I enter this http://localhost:17920 as a default URL, then http://localhost:17920/dashboard should be displayed by default. Thanks.

1 Answers

You need to define RoutePrefix over the Controller like below. Also update your Route("dashboard") to Route("Home") because that is your default action name on route configuration.

[RoutePrefix("Law")]
public class LawController : Controller
{
    [Route("Home")]
    [ActionName("Home")]
    public ActionResult Home()
    {
        return View();
    }
    
    // Other action methods
}

Please also refer https://devblogs.microsoft.com/aspnet/attribute-routing-in-asp-net-mvc-5/ for more details.


Edit As per edit in your question it is more clear what you want. From your existing code you just need to add one more Route over LawController's Home action as below, so it could match http://localhost:17920/ & http://localhost:17920/dashboard to that action method.

public class LawController : Controller
{
    [Route("")]
    [Route("dashboard")]
    [ActionName("Home")]
    public ActionResult Home()
    {
        return View();
    }
    
    [Route("alert")]
    [ActionName("alert-list")]
    public ActionResult AlertList()
    {
        return View();
    }
Related