我有一个用于返回某些 HTTP 错误的自定义 ActionResult,例如 NotFoundResult 和 ForbiddenResult,它们都派生自 ViewResult。
请允许我向您建议一种替代错误处理:
首先创建一个错误控制器和相应的视图:
public class ErrorController : Controller
{
public ActionResult General()
{
return View();
}
public ActionResult HttpError404()
{
return View();
}
public ActionResult HttpError500()
{
return View();
}
}
在Global.asax
定义Application_Error
方法中:
protected void Application_Error(object sender, EventArgs e)
{
var exception = Server.GetLastError();
// TODO: Log the exception with your favorite logging framework
Response.Clear();
var httpException = exception as HttpException;
var routeData = new RouteData();
// Take the ErrorController
routeData.Values.Add("controller", "error");
if (httpException == null)
{
// Use the General action for any unhandled error
routeData.Values.Add("action", "general");
}
else
{
switch (httpException.GetHttpCode())
{
case 404:
routeData.Values.Add("action", "httpError404");
break;
case 500:
routeData.Values.Add("action", "httpError500");
break;
default:
routeData.Values.Add("action", "general");
break;
}
}
// Add the exception to route data so that the error controller
// could use it with RouteData.Values["error"]
routeData.Values.Add("error", exception);
Server.ClearError();
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
最后抛出适当的异常:
public class HomeController: Controller
{
public ActionResult Index(int id)
{
var model = _repository.GetModel(id);
if (model == null)
{
throw new HttpException(404, "Model not found with id = " + id);
}
return View(model);
}
}