【问题标题】:Redirect to Named Route from RouteConfig or Controller Action Method从 RouteConfig 或控制器操作方法重定向到命名路由
【发布时间】:2017-11-18 22:49:08
【问题描述】:

我在 ASP.NET MVC 中有以下命名路由:

[Route("build", Name = "Build")]
public ActionResult Build()
{
    return View();
}

我有一个情况,这个应用程序不再有主页,不需要 /Home/Index.cshtml。但是,我不想删除 Index.cshtml,也不想将 Build.cshtml 代码移动到 Index.cshtml

我只是希望默认路由成为我的构建路由。不幸的是,有了命名的构建路线[Route("build", Name = "Build")],我在整个应用程序中都使用了@Html.RouteLink("GET BUILDING", "Build"),所以我无法通过以下任何一种方式从http://www.mywebsite.comhttp://www.mywebsite.com/build 进行简单的重定向:

在我的RouteConfig中,这个不行,去http://wwww.mywebsite.com时找不到资源:

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

还有,这个更奇怪的是,这个也不行,还导致去http://wwww.mywebsite.com时找不到资源:

public ActionResult Index()
{
    return RedirectToRoute("Build");
}

我像这样注释掉我命名的路线:

//[Route("build", Name = "Build")]
public ActionResult Build()
{
    return View();
}

那么我上面的 RouteConfig 方法就可以了。

我更愿意重定向到我的 RouteConfig 中的命名路由,尽管如果我可以从我的 /home/index 操作方法重定向到命名路由也很好

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    RouteLink 采用路由名称,而不是路由模式/模板,因此您只需将路由模式更改为 ""(空字符串)

    [Route("", Name = "Build")]
    public ActionResult Build()
    {
        return View();
    }
    

    当一个请求来到yourSiteName.com时,它会被Build操作方法处理,因为它与路由模式匹配(baseurl后面什么都没有

    所有在 RouteLink 辅助方法中使用路由名称的现有代码仍然可以工作,因为我们没有更改它。

    @Html.RouteLink("GET BUILDING", "Build") 
    

    如果您想让yourSiteName/Build 也能正常工作,您可以添加另一个路由模式为 "" 的路由以及您当前的路由定义。

    [Route("")]
    [Route("build", Name = "Build")]
    public ActionResult Build()
    {
        return View();
    }
    

    现在当yourSiteName.comyourSiteName.com/build 的请求到来时,将由Build 操作方法处理

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多