简体   繁体   中英

Setting default route in C# MVC

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.

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();
    }

you should set route on the class

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM