0

我有一个 ASP.NET Web Forms APP,我想一次将它迁移到 ASP.NET MVC。我已将 MVC 设置为在 webforms 应用程序中运行。我已经正确设置了所有内容,如果我将 ASP.NET MVC 文件夹(控制器、视图)放在项目中名为 MVC 的子文件夹中,并将我的全局 asax 中的路由设置为

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
    routes.MapRoute("Default", // Route name
        "w/{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = "" } // Parameter defaults
    );
}

protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
}

所有配置和程序集引用均已设置。如果我进行调试,我可以在我的 Home 控制器上的 Index 方法中设置一个断点。

public class HomeController
    : Controller
{
    public ActionResult Index()
    {
        this.HttpContext.Trace.Write("Hrm...");
        return View("index", (object)"Hello");
    }
}

正在发生的问题是

return View("index", (object)"Hello");

如果 MVC 无法找到视图,则通常不会返回错误状态代码或您期望的搜索列表。相反,我收到了 200 个 http 响应,而响应的内容正文中没有任何内容。

这是http请求的详细信息:

GET http://localhost.:2396/w/home/index2 HTTP/1.1
Accept: */*
Accept-Language: en-us
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; MS-RTC LM 8; InfoPath.2; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E)
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Host: localhost.:2396
Pragma: no-cache
Cookie: ASP.NET_SessionId=3yqf2t55sckemhmxq2bhibmq

HTTP/1.1 200 OK
Server: ASP.NET Development Server/9.0.0.0
Date: Wed, 09 May 2012 12:42:43 GMT
X-AspNetMvc-Version: 2.0
Cache-Control: private
Content-Length: 0
Connection: Close

上面的请求转到 index2,这是一个不存在的操作,它不会给我一个错误。我怀疑索引操作中的 ViewResult 正在引发异常,但不知何故它在某处被抑制了。我继承了这个代码库,所以我只是想弄清楚发生了什么。

在 web.config 我已经配置了错误处理,这样我应该能够看到任何错误消息,但这仍然不能解释为什么 http 状态代码总是 200。

<customErrors mode="Off"/>

<httpErrors errorMode="DetailedLocalOnly"/>

另一个快速说明,如果我更换

return View("index", (object)"Hello");

return Content("abc");

它将在 http 响应的内容正文中正确输出“abc”。

有任何想法吗?

4

1 回答 1

2

似乎您的视图位置错误,因为您提到控制器,视图位于名为“MVC”的文件夹下。

“Views”文件夹应该在根目录下,即 ViewEngine 查找视图的地方。

更新: 您可以使用自定义 ViewEngine 覆盖此默认行为。对于该实现IViewEngine接口,它有一个名为的方法FindView,您可以在其中实现自己的逻辑来扫描不同的位置。

于 2012-05-09T14:07:36.087 回答