我在ASP.NET MVC中实现了一个自定义控制器工厂,我在global.ascx
中注册了它。这个想法是处理404的情况以及控制器构造函数中的异常。我知道工厂已被分配到ASP.NET MVC,因为在请求时,我可以介入它。我可以看到我正在返回我认为的控制器。但为什么,为什么在地球上,不是我的控制器使用?但是我认为我会得到通常的动作没有发现异常,而不是控制器......概念我想知道这是否是最合适的地方。
protected override IController GetControllerInstance
(RequestContext context,
Type controllerType)
{
IController controller = null;
try
{
controller = base.GetControllerInstance(context, controllerType);
}
catch (CurrentSessionException)
{
controller = new LoginController();
}
catch (System.Web.HttpException)
{
controller = new ErrorController();
}
catch (System.Exception)
{
controller = new ErrorController();
}
return controller;
}
答案 0 :(得分:0)
尝试手动清除catch语句中的错误。
requestContext.HttpContext.ClearError();
理想情况下,最好将其作为过滤器处理。 MVC带有HandleErrorAttribute
,您可以将其子类化。您可以覆盖OnException
方法,然后根据需要简单地处理逻辑。
默认情况下,这是MVC 3所做的。
public virtual void OnException(ExceptionContext filterContext) {
if (filterContext == null) {
throw new ArgumentNullException("filterContext");
}
if (filterContext.IsChildAction) {
return;
}
// If custom errors are disabled, we need to let the normal ASP.NET exception handler
// execute so that the user can see useful debugging information.
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) {
return;
}
Exception exception = filterContext.Exception;
// If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
// ignore it.
if (new HttpException(null, exception).GetHttpCode() != 500) {
return;
}
if (!ExceptionType.IsInstanceOfType(exception)) {
return;
}
string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];
HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult {
ViewName = View,
MasterName = Master,
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 500;
// Certain versions of IIS will sometimes use their own error page when
// they detect a server error. Setting this property indicates that we
// want it to try to render ASP.NET MVC's error page instead.
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}