2

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.

2
  • do you have other routes in the routes object ? Commented Dec 17, 2020 at 8:00
  • Yes, i do have. Commented Dec 17, 2020 at 8:47

1 Answer 1

3

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();
    }
Sign up to request clarification or add additional context in comments.

2 Comments

localhost:17920/list and localhost:17920 both returns an error page (resources cannot be found.)
Yes it worked. [Route("")] works. Thanks Karan

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.