我在全局文件Global.asax中使用这段代码来捕获所有404错误并将它们重定向到自定义控制器/视图。
我目前有三个控制器,分别为
当我输入像
然而,如果我输入一个无效的控制器名称,例如
以下是我的ErrorController:
我的观点是:
protected void Application_Error(object sender, EventArgs e) {
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null) {
if (httpException.GetHttpCode() == 404) {
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
Server.ClearError();
IController errorController = new webbage.chat.Controllers.ErrorController();
Response.StatusCode = 404;
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
}
}
我目前有三个控制器,分别为
Users
、Rooms
和Home
,这些都与我的应用程序相关。当我输入像
{localhost}/rooms/999
这样的内容时(因为999是无效的房间ID,所以会导致它抛出404错误),重定向和呈现都很好,一切正常。然而,如果我输入一个无效的控制器名称,例如
{localhost}/test
,它会将其重定向到视图,但在呈现时它只是普通文本的HTML。有人能指出这是为什么吗?以下是我的ErrorController:
public class ErrorController : Controller {
public ActionResult Index() {
return View();
}
public ActionResult NotFound() {
return View();
}
public ActionResult Forbidden() {
return View();
}
}
我的观点是:
@{
ViewBag.Title = "Error";
}
<div class="container">
<h1 class="text-pumpkin">Ruh-roh</h1>
<h3 class="text-wet-asphalt">The page you're looking for isn't here.</h3>
</div>
编辑
我最终选择只使用web.config错误处理,因为它更加简单。我从Global.asax文件中删除了Application_Error代码,并在web.confg文件中添加了以下片段:
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="403"/>
<remove statusCode="404"/>
<remove statusCode="500"/>
<error statusCode="403" responseMode="ExecuteURL" path="/Error/Forbidden" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
<error statusCode="500" responseMode="ExecuteURL" path="/Error" />
</httpErrors>
</system.webServer>
不过,我仍然想知道为什么会发生这种情况。