ASP.NET MVC 5中的自定义错误页面
我想在我的项目中添加自定义错误页面。 我发现这篇关于我的问题的post ,我尝试实现它。
所以:
- 我添加了
404.cshtml
,404.html
,500.cshtml
和500.html
页面 - 在添加的cshtml文件中设置响应状态代码
- 注释将
HandleErrorAttribute
添加到全局filter - 更新我的web.config文件
但现在当我尝试通过路径http://localhost:120/foo/bar
,我的应用程序在http://localhost:120
我得到下一页:
‘/’应用程序中的服务器错误。
运行时错误
描述:处理您的请求时发生exception。 此外,执行第一个exception的自定义错误页面时发生另一个exception。 请求已终止。
我设置<customErrors mode="Off"
以查看问题所在。 它是 – The resource cannot be found.
这是合乎逻辑的。 但是当我设置<customErrors mode="On"
– 我再次得到运行时错误。
是什么导致它以及如何解决它?
我的配置文件:
IIS 8.5版
您使用的是哪个版本的IIS? 如果7+然后使用
忽略自定义错误并使用
。 使用下面的方法,后者将显示您的错误页面而不更改URL,IMO是处理这些事情的首选方式。
设置一个错误控制器并将你的404和500放在那里:
在控制器中:
public class ErrorController : Controller { public ActionResult servererror() { Response.TrySkipIisCustomErrors = true; Response.StatusCode = (int)HttpStatusCode.InternalServerError; return View(); } public ActionResult notfound() { Response.TrySkipIisCustomErrors = true; Response.StatusCode = (int)HttpStatusCode.NotFound; return View(); } }
然后显然为每个覆盖的错误设置相应的视图。
您的重定向url不正确。 制作~/404.html
和~/500.html
。 请注意,我从.cshtml
更改了扩展名。 确保文件存在,并指向正确的位置。
我必须做以下事情:
- 从httpErrors中删除defaultPath,从customErrors中删除defaultRedirect。
-
确保在Global.asax中我注册了一个默认路由:
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { action = "Index", id = UrlParameter.Optional });
我不确定为什么第1步是必要的,第2步是因为我们正在做EPiServer。