【问题标题】:Why does web root give a 404 in ASP.Net MVC 5为什么 web root 在 ASP.Net MVC 5 中给出 404
【发布时间】:2018-01-02 01:40:36
【问题描述】:

我有一个 ASP.Net MVC 5 站点,我在其中更改了 Home 控制器中的路由以删除 Home 部分。

我的家庭控制器看起来像

    [Route("Index")]
    public ActionResult Index()
    {
        ViewBag.Title = "Home";
        ViewBag.Current = "Home";

        return View();
    }

当我转到 http://localhost:29033/Index 时效果很好,但是当我转到 http://localhost:29033 时出现以下错误:

在控制器“MyProject.Controllers.HomeController”上找不到公共操作方法“Index”。

我的 RegisterRoutes 看起来像:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.LowercaseUrls = true;

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("elmah.axd");

        routes.MapMvcAttributeRoutes();

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

任何帮助将不胜感激。

【问题讨论】:

  • 您使用[Route("Index")]的任何具体原因?
  • 是的,我希望页面通过 www.myurl.com/Index 而不是 www.myurl.com/home/index。我个人不在乎,但用户出于某种原因这样做

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


【解决方案1】:

鉴于这里似乎正在使用属性路由,我相信您需要更新您的路由以获得所需的行为

[RoutePrefix("home")]
public class HomeController : Controller {

    [Route("Index")] // Matches GET home/index
    [Route("~/", Name = "root")] //Matches GET /
    public ActionResult Index() {
        //...code removed for brevity
    }    

}

参考Attribute Routing in ASP.NET MVC 5

【讨论】:

  • 谢谢!这正是我所需要的。
猜你喜欢
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 2014-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多