这一定很简单并且已经回答了,但我浪费了很多时间。我无法弄清楚如何在错误输入的地址上获取错误页面。此外,我不想重定向,但保留URL。我已经尝试过很多CustomErrors,HttpErrors和Application_Error的组合,但是对于不存在的控制器没有任何作用 - 取决于HttpErrors我总是得到IIS 404.0页面或只是一个空的404响应。在IIS 7.5,MVC 3上运行。
答案 0 :(得分:0)
我使用以下路线确保所有不匹配任何其他路线的请求都落在那里,然后您可以非常轻松地处理这种情况:
// this route is intended to catch 404 Not Found errors instead of bubbling them all the way up to IIS.
routes.MapRoute(
"PageNotFound",
"{*catchall}",
new { controller = "Error", action = "NotFound" }
);
映射最后一个(在任何其他.MapRoute
语句之后包含该语句)。
答案 1 :(得分:0)
我不记得我在哪里得到了解决方案。但这是处理错误的代码: 首先,创建一个ErrorController:
public class ErrorController : Controller
{
//
// GET: /Error/
public ActionResult Index()
{
return RedirectToAction("Index", "Home");
}
public ActionResult Generic()
{
Exception ex = null;
try
{
ex = (Exception)HttpContext.Application[Request.UserHostAddress.ToString()];
}
catch { }
return View();
}
public ActionResult Error404()
{
return View();
}
}
其次,打开Global文件并添加以下代码:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Application[HttpContext.Current.Request.UserHostAddress.ToString()] = ex;
}
第三,在webconfig中更改customerror:
<customErrors mode="Off" defaultRedirect="/Error/Generic">
<error statusCode="404" redirect="/Error/Error404"/>
</customErrors>
更多:我创建了一个错误布局。它使事情变得更加清晰。 :)
希望这会对你有所帮助。