【问题标题】:MVC Web App Error HTTP 404MVC Web 应用程序错误 HTTP 404
【发布时间】:2015-11-03 19:09:44
【问题描述】:

我正在编写 MVC 教程,并且正在编写一个非常基本的 Web 应用程序。

这是我的 Controller 文件夹中的 Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FirstMVCApplication.Controllers
{
    public class HomeContoller : Controller
    {
        //
        // GET: /HomeContoller/

        public ActionResult Index()
        {
            int hour = DateTime.Now.Hour;

            ViewBag.Greeting =
            hour < 12
            ? "Good Morning. Time is" + DateTime.Now.ToShortTimeString()
            : "Good Afternoon. Time is " + DateTime.Now.ToShortTimeString();

            return View();
        }

    }
}

这是我在视图文件夹中的视图:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @ViewBag.Greeting (<b>From Index View</b>)
    </div>
</body>
</html>

我正在使用 Razor。

当我执行它时,它返回一个未找到的 HTTP 404 资源。它是一个空的 Web MVC-4 应用程序。

编辑 路由配置

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

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

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

【问题讨论】:

  • 此视图必须位于 Views/Home 文件夹中。您应该在浏览器中发布路由配置文件和正在输入的 url。
  • 这里有两点:1- 4XX 错误,表示您(用户,而不是服务器)做错了什么。 2- 404 = 未找到您请求的资源,可能是您使用了错误的 url。请告诉我们浏览器中显示的网址
  • 它是 http://localhost:55171/
  • 您的视图应位于/Views/Home 中并命名为Index.cshtml。您可以尝试更明确的路由http://localhost:55171/Home/Index。而且你还重新编译,清除了缓存,并杀死了系统托盘中的开发 Web 服务器?

标签: asp.net-mvc-4 c#-4.0 razor


【解决方案1】:

删除这个@{ Layout = null; } 来自您在此处发布的 Layout.cshtml 文件

将@RenderBody() 添加到您在此处发布的 Layout.cshtml 文件中

在您在这里拥有的 Index.cshtml 文件中。在页面文件顶部添加

@{ 布局 = "~/Views/Shared/Layout.cshtml"; }

【讨论】:

  • 我的视图叫做Index.cshtml 所以你说我写@RenderBody() 并删除@{ Layout = null; } Index.cshtml 文件呢?我只有一种看法。您说/Views/Shared/,但视图位于Views 文件夹内,仅此而已。我是否必须在我的 Views 文件夹中创建另一个名为 Shared 的文件夹?还有,我在哪里写@{ Layout = "~/Views/Shared/Layout.cshtml"; }
猜你喜欢
  • 2016-07-14
  • 1970-01-01
  • 2018-09-17
  • 2016-10-11
  • 2020-10-18
  • 2016-06-11
  • 2015-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多