【发布时间】:2014-02-20 14:04:53
【问题描述】:
我想用我自己的模型为我的 MVC4 项目创建一个自定义错误页面。
我使用了来自 Custom error pages on asp.net MVC3 的 Darin Dimitrov 的方法
现在我想使用我自己的(测试)模型:
public class ErrorModel
{
public string message { get; set; }
}
现在,当我使用 customErrors mode="Off" 时,一切正常,但仅在本地计算机上。当我从远程机器访问机器时,会显示默认错误。 (这是预期的方式 - 我猜)
现在当我设置系统突然期待他自己的模型而不是我的:
“传入字典的模型项是‘System.Web.Mvc.HandleErrorInfo’类型的,但是这个字典需要一个‘Project.Controllers.ErrorModel’类型的模型项。
当模式为 Off 时,我如何强制系统通过 customErrors="Off" 向远程系统显示页面,或者如何强制他使用我的模型而不是 HandleErrorInfo 模型?
我的错误控制器
public class ErrorController : Controller
{
public ActionResult General(Exception exception)
{
var viewModel = new ErrorModel()
{
message = exception.Message
};
return View(viewModel);
}
观点:
@model SRMv2.WebUI.Controllers.ErrorModel
@{
}
@Html.Raw(Model.message)
在 Global.asax 中
protected void Application_Error()
{
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false); HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Errors";
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;
}
}
IController errorController = new ErrorController();
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
errorController.Execute(rc);
}
【问题讨论】:
-
为什么 customErrors="Off" 会显示您的自定义错误消息?也许其他地方有问题。
-
因为我在 Application_Error 上调用 Global.asax 中的 ErrorController,见:stackoverflow.com/questions/5226791/…
标签: c# asp.net-mvc asp.net-mvc-4 custom-error-pages