Rob*_*Rob 5 error-handling asp.net-mvc-3
使用博客张贴在这里和一个主题在这里,所以我已经创建了一个控制器,它应该处理我所有的错误页面.
在我的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);
}
Run Code Online (Sandbox Code Playgroud)
我的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");
}
}
Run Code Online (Sandbox Code Playgroud)
而我的Razor View只包含下面的html片段;
@{
ViewBag.Title = "404";
}
<h2>404</h2>
This is a 404 page!
Run Code Online (Sandbox Code Playgroud)
当我使用Return Content时,我得到一个纯文本输出,告诉我我正在看404页.但是,我希望404页面适合我的其余设计,所以我想使用自己的视图.但是,只要我使用Return View,我就会得到一个空白页面.我希望遗漏一些非常明显的东西,但我没有看到它.
我遇到了同样的问题,终于找到了对我有用的解决方案。当我在线上放置断点errorsController.Execute(rc);并使用“step into”直到遇到此异常时,突破出现了:
The view 'Detail' or its master was not found or no view engine supports the
searched locations. The following locations were searched:
~/Views/Errors/Detail.aspx
~/Views/Errors/Detail.ascx
~/Views/Shared/Detail.aspx
~/Views/Shared/Detail.ascx
~/Views/Errors/Detail.cshtml
~/Views/Errors/Detail.vbhtml
~/Views/Shared/Detail.cshtml
~/Views/Shared/Detail.vbhtml
Run Code Online (Sandbox Code Playgroud)
我认为异常被吞没了,因为它发生在 Application_Error 方法内部,并且因为我已经设置了Response.TrySkipIisCustomErrors = true.
看到这个错误后,我很快意识到我的问题只是名称不匹配之一:我的控制器实际上命名ErrorController时没有 's',而不是ErrorsController。对我来说问题是我设置了routeData.Values["controller"] = "Errors";,这是错误的。切换它来routeData.Values["controller"] = "Error";解决问题。
请注意,您不会立即捕获错误,因为您直接实例化控制器,并且如果该部分拼写错误,它将无法编译。但在控制器内部,调用 View() 将使用RouteData我们构造并传递给RequestContext对象的实例来查找视图。因此,如果控制器名称拼写错误,MVC 将不知道在哪里查找视图,并且由于跳过了 IIS 自定义错误,因此它会默默地失败。
长话短说:检查您的控制器和视图名称。我假设如果控制器名称正确,但视图的文件名不匹配,则会发生类似的情况。
| 归档时间: |
|
| 查看次数: |
2839 次 |
| 最近记录: |