【问题标题】:ASP.NET page automatically opens with defined route instead of Home/IndexASP.NET 页面使用定义的路由而不是 Home/Index 自动打开
【发布时间】:2021-07-10 17:08:49
【问题描述】:

我根据控制器中定义的路由值定义了路由映射以打开页面。

当我在主文件夹下运行index.cshtml 时,它以https://localhost:44333/Home/Index 打开页面但没有结果,但我已经在控制器的索引函数中定义了路由。当我将 url 更改为 https://localhost:44333/MainPage 时,它以 https://localhost:44333/MainPage 打开页面。

如何在运行应用程序时自动打开带有此 URL https://localhost:44333/MainPage 或“https://localhost:44333/”的页面。

这是我的HomeControllerIndex 函数,定义如下。

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

这是我的 RouteConfig.cs 文件,如下所示。

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

        }
    }

这是我的管理部分

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

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

当我以/Admin/Index 运行应用程序并将网址显示为panel/login 时,如何执行相同的过程?

【问题讨论】:

    标签: asp.net-mvc url routes


    【解决方案1】:

    如果您想为路由设置不同的 URL,请使用 RoutePrefix

    如果您想打开 panel/login 而不是 /admin/index,这里是一个示例:

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

    对于 ActionResult:

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

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 2020-05-06
      • 2010-10-07
      • 2023-03-24
      • 2018-10-18
      相关资源
      最近更新 更多