使用此处发布的博客和此处的主题,我创建了一个控制器,该控制器应处理我的所有错误页面。
在我的 Global.asax.cs 中,我有以下代码:
protected void Application_Error()
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
var routeData = new RouteData();
Response.Clear();
Server.ClearError();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = "General";
routeData.Values["exception"] = exception;
Response.StatusCode = 500;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
case 403:
routeData.Values["action"] = "Http403";
break;
case 404:
routeData.Values["action"] = "Http404";
break;
}
}
// Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;
IController errorsController = new ErrorController();
HttpContextWrapper wrapper = new HttpContextWrapper(Context);
var rc = new RequestContext(wrapper, routeData);
errorsController.Execute(rc);
}
我的 ErrorController 看起来像这样:
public class ErrorController : BaseController
{
/// <summary>
/// Returns a default view for not having access.
/// </summary>
public ActionResult Unauthorized()
{
BaseModel viewModel = new BaseModel
{
LoginModel = new LogonModel(),
ProfessionsTopX = GetTopXProfessions()
};
return View(viewModel);
}
public ActionResult General(Exception exception)
{
return View("Exception", exception);
}
public ActionResult Http404()
{
//This line works
//return Content("Not found", "text/plain");
//This line presents a blank page
return View("404","_Layout");
}
public ActionResult Http403()
{
return View("403", "_Layout");
}
}
而我的 Razor View 只包含下面的一段 html;
@{
ViewBag.Title = "404";
}
<h2>404</h2>
This is a 404 page!
当我使用返回内容时,我得到一个纯文本输出,告诉我我正在查看 404 页。但是,我希望 404 页面适合我的设计的其余部分,所以我想使用我自己的视图。但是,一旦我使用返回视图,我就会得到一个空白页。我希望遗漏一些非常明显的东西,但我没有看到。