ASP.NET page automatically opens with defined route instead of Home/Index

Viewed 51

I defined route mapping to open pages with respect to defined route value in Controller.

When I run index.cshtml under Home Folder, it pages open with https://localhost:44333/Home/Index with no result but I already defined route in Index function of Controller. When I changed url to https://localhost:44333/MainPage, it pages open with https://localhost:44333/MainPage.

How can I open page with this url https://localhost:44333/MainPage or "https://localhost:44333/" automatically when I run the app.

Here is my Index function of HomeController which is defined below.

[RequireHttps]
[Route("")]
[Route("MainPage")]
public ActionResult Index()
{
   ViewBag.Attribute = "header-transparent";
   return View();
}

Here is my RouteConfig.cs file which is shown below.

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapMvcAttributeRoutes();

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

        }
    }

Here is my admin part

[Route("panel")]
        public ActionResult Index()
        {
            var allCategories = db.Category.ToList();
            return View(allCategories);
        }

        [Route("panel/login")]
        public ActionResult Login()
        {
            return View();
        }

How can do the same process when I run app as /Admin/Index and show the url as panel/login?

1 Answers

If you want to set a different URL for your route, use RoutePrefix.

Here is an example if you want to open panel/login instead of /admin/index:

[RoutePrefix("panel")]
public class AdminController : Controller

And for ActionResult:

[Route("Login")]
public ActionResult Index()
Related