我有一个MVC3网站,我正在尝试为从数据库访问内容的小型网站构建自定义错误。
在我的配置中,我得到了:
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="/404" />
<error statusCode="500" redirect="/error/500.html" />
</customErrors>
当我直接在浏览器中访问它时,/ 404路由可以正常工作。
现在标准的“未找到404页面”显示。
在我的控制器中,我得到了:
public ActionResult ShowPage(int test)
{
var page = _rep.GetPage(test);
if(page == null)
return HttpNotFound();
//....
}
这里可能缺少什么?感觉像配置中缺少的东西
答案 0 :(得分:2)
对于自定义错误,我总是将以下方法放在global.asax中,这将激活我的错误控制器(基于此SO回答https://stackoverflow.com/a/5229581/426840):
protected void Application_Error()
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
// Don't execute error controller for custom error mesages when custom error is disabled
if (!HttpContext.Current.IsCustomErrorEnabled) return;
Response.Clear();
Server.ClearError();
Response.StatusCode = 500;
// Avoid IIS messing with custome errors https://stackoverflow.com/a/1719474/426840
// Also https://stackoverflow.com/a/2345742/426840 for web.config
Response.TrySkipIisCustomErrors = true;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
}
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = Response.StatusCode != 404 ? "Index" : "NotFound";
routeData.Values["exception"] = exception;
routeData.Values["logId"] = logId;
IController errorsController = new ErrorController();
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
errorsController.Execute(rc);
}
错误控制器:
public class ErrorController : AuthorizedController
{
public ActionResult Index(string logId)
{
if (Request.IsAjaxRequest())
{
return new HttpStatusCodeResult(Response.StatusCode, Response.StatusDescription);
}
ViewBag.HttpStatusCode = Response.StatusCode;
ViewBag.HttpStatusMessage = Response.StatusDescription;
ViewBag.LogId = logId;
return View("Error");
}
public ActionResult NotFound(string logId)
{
if (Request.IsAjaxRequest())
{
return new HttpStatusCodeResult(Response.StatusCode, Response.StatusDescription);
}
ViewBag.HttpStatusCode = Response.StatusCode;
ViewBag.HttpStatusMessage = Response.StatusDescription;
ViewBag.LogId = logId;
return View("NotFound");
}
}
的Web.config:
<customErrors mode="On" />
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<!-- Avoid IIS messing with custom errors https://stackoverflow.com/a/2345742/426840 -->
<httpErrors existingResponse="PassThrough" />
</system.webServer>
这适用于404,但也适用于所有其他错误。
答案 1 :(得分:1)
HttpNotFound
结果返回一个空视图。你需要抛出异常
if(page == null)
throw new HttpException(404, "Not found")