【问题标题】:Setting default route in C# MVC在 C# MVC 中设置默认路由
【发布时间】:2020-12-17 19:23:26
【问题描述】:

我正在 C# MVC 中创建一个项目并使用操作。由于要求,现在我使用 Route 来隐藏控制器名称并仅显示页面名称。

路由配置

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

控制器 1(访问:http://localhost:17920/dashboard)和(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();
        }

控制器 2(访问:http://localhost:17920/list)

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

我正在尝试的是当我输入这个 http://localhost:17920 作为默认 URL 时,应该默认显示 http://localhost:17920/dashboard。 谢谢。

【问题讨论】:

  • 路由对象中还有其他路由吗?
  • 是的,我有。

标签: c# asp.net-mvc model-view-controller


【解决方案1】:

您需要在Controller 上定义RoutePrefix,如下所示。还将您的Route("dashboard") 更新为Route("Home"),因为这是您在路由配置中的默认操作名称。

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

更多详情请参考https://devblogs.microsoft.com/aspnet/attribute-routing-in-asp-net-mvc-5/


编辑根据您问题中的编辑,您更清楚您想要什么。从您现有的代码中,您只需在LawControllerHome 操作上再添加一个Route,如下所示,这样它就可以将http://localhost:17920/http://localhost:17920/dashboardaction 方法相匹配。

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-09
相关资源
最近更新 更多