//Обработка ошибок для всего приложения protected void Application_Error(object sender, EventArgs e) { string requestType=Request.RequestType; if (requestType.Equals("GET")) { HttpContext ctx = HttpContext.Current; Exception ex = ctx.Server.GetLastError(); var httpException = ex as HttpException; if (httpException != null) { if (httpException.GetHttpCode() == 404) { ctx.Response.Clear(); RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext; IController controller = new HomeController(); // Здесь можно использовать любой контроллер var context = new ControllerContext(rc, (ControllerBase)controller); var viewResult = new ViewResult(); //страницы будут искаться в Views/Shared viewResult.ViewName = "Error404"; viewResult.ViewData.Model = new HandleErrorInfo(ex, context.RouteData.GetRequiredString("controller"), context.RouteData.GetRequiredString("action")); viewResult.ExecuteResult(context); ctx.Server.ClearError(); } } } }
protected void Application_Error() { try { var logger = ObjectFactory.GetInstance<ILog>(); Exception exception = Server.GetLastError() ?? new Exception("Unable to get exception."); logger.Fatal("An unhandled exception occurred.", exception); } catch { } HttpContext ctx = HttpContext.Current; ctx.Response.Clear(); RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext; string controllerName = rc.RouteData.GetRequiredString("controller"); IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory(); IController controller = factory.CreateController(rc, controllerName); var cc = new ControllerContext(rc, (ControllerBase)controller); var viewResult = new ViewResult { ViewName = "Error" }; viewResult.ExecuteResult(cc); ctx.Server.ClearError(); }
private static void RedirectToError() { HttpContext ctx = HttpContext.Current; var errorMessage = Convert.ToString(ctx.Server.GetLastError()); var error = new KeyValuePair<string, object>("ErrorMessage", errorMessage); foreach (var er in ctx.AllErrors) { InternalLog.WriteLog(HttpContext.Current.Request.UserAgent, HttpContext.Current.Request.Url.ToString(), er.Message, er.StackTrace.ToString()); } ctx.Response.Clear(); if (ctx.CurrentHandler != null && ctx.CurrentHandler.GetType().ToString().Equals("System.Web.Mvc.MvcHandler")) { RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext; IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory(); IController controller = factory.CreateController(rc, "Home"); var cc = new ControllerContext(rc, (ControllerBase)controller); var viewResult = new ViewResult { ViewName = "InternalError" }; viewResult.ViewData.Add(error); viewResult.ExecuteResult(cc); ctx.Response.End(); } }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } var response = context.HttpContext.Response; var request = context.HttpContext.Request; var requestedUrl = GetRequestedUrl(request); NotFoundConfig.OnNotFound(context.RequestContext.HttpContext.Request, new Uri(requestedUrl)); this.ViewData["RequestedUrl"] = requestedUrl; this.ViewData["ReferrerUrl"] = GetReferrerUrl(request, request.Url.OriginalString); // Make sure the status code is 404 for the search engine bots response.StatusCode = 404; // Prevent IIS7 from overwriting our error page! response.TrySkipIisCustomErrors = true; var viewResult = new ViewResult { ViewName = this.ViewName, ViewData = this.ViewData }; response.Clear(); viewResult.ExecuteResult(context); }
public void Execute(GenericResult genericResult, ControllerContext controllerContext) { if (genericResult.Refresh) { new RedirectResult(controllerContext.HttpContext.Request.RawUrl).ExecuteResult(controllerContext); return; } if (genericResult.RedirectUri != null) { new RedirectResult(genericResult.RedirectUri.ToString()).ExecuteResult(controllerContext); return; } var viewName = genericResult.ResultName ?? (string)controllerContext.RouteData.Values["action"]; ViewEngineResult view = ViewEngines.Engines.FindView(controllerContext, viewName, null); if (view.View == null) return; var viewResult = new ViewResult(); controllerContext.Controller.ViewData.Model = genericResult.Model; viewResult.ViewName = viewName; viewResult.ViewData = controllerContext.Controller.ViewData; viewResult.TempData = controllerContext.Controller.TempData; foreach (var message in genericResult.Messages.Where(m => m.Category == MessageCategory.Error)) controllerContext.Controller.ViewData.ModelState.AddModelError(message.Field ?? message.Text, message.Text); viewResult.ExecuteResult(controllerContext); }
public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; var request = context.HttpContext.Request; // TODO: Add logic for not authorized requests string viewName = StatusCode == HttpStatusCode.NotFound ? NotFoundView : ErrorView; // We need to clear both headers and content // because Clear() doesn't clear the headers // see: http://msdn.microsoft.com/en-us/library/system.web.httpresponse.clear.aspx response.ClearHeaders(); response.ClearContent(); response.StatusCode = (int)StatusCode; // 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. response.TrySkipIisCustomErrors = true; if (request.IsAjaxRequest()) { // TODO: Add logic for AJAX requests } var viewResult = new ViewResult { ViewName = viewName, ViewData = ViewData ?? new ViewDataDictionary() }; viewResult.ExecuteResult(context); }
private void ExecuteResult(ControllerBase controller) { var result = new ViewResult { ViewData = controller.ViewData, TempData = controller.TempData }; result.ExecuteResult(controller.ControllerContext); }
public override void Execute(object model, ControllerContext context) { context.HttpContext = new HttpContextWrapper(HttpContext.Current); var viewResult = new ViewResult {TempData = context.Controller.TempData, ViewData = context.Controller.ViewData}; viewResult.ViewData.Model = null; viewResult.ExecuteResult(context); }
private new ActionResult View(string viewFolder, string viewName, object model = null) { var view = new ViewResult(); view.TempData = TempData; view.ViewName = (viewFolder != null ? ("~/Views/" + viewFolder + "/" + viewName + ".cshtml") : viewName); view.ViewData = ViewData; view.ViewData.Model = model; view.ExecuteResult(ControllerContext); return null; }
protected void Application_Error() { ErrorLoger.LogEventError(Server.GetLastError()); ErrorLoger.LogEventError(Context.Error); Response.Clear(); Server.ClearError(); var res = new ViewResult {ViewName = "Error"}; res.ExecuteResult(new ControllerContext(Request.RequestContext, (ControllerBase) new HomeController())); }
protected void Application_Error(object sender, EventArgs e) { HttpContext ctx = HttpContext.Current; Exception ex = ctx.Server.GetLastError(); ctx.Response.Clear(); RequestContext rc = ((MvcHandler) ctx.CurrentHandler).RequestContext; IController controller = new ErrorController(); var context = new ControllerContext(rc, (ControllerBase) controller); var viewResult = new ViewResult(); if (ex is HttpRequestValidationException) viewResult.ViewName = "HttpRequestValidationException"; else { var httpException = ex as HttpException; if (httpException != null) { switch (httpException.GetHttpCode()) { case 404: viewResult.ViewName = "Error404"; break; case 500: viewResult.ViewName = "Error500"; break; default: viewResult.ViewName = "Error"; break; } } else { viewResult.ViewName = "Error"; } } context.RouteData.Values["controller"] = "Error"; context.RouteData.Values["action"] = viewResult.ViewName; context.RouteData.Values["exception"] = ex; viewResult.ViewData.Model = new HandleErrorInfo(ex, context.RouteData.GetRequiredString("controller"), context.RouteData.GetRequiredString("action")); log.Error(ex.Message); viewResult.ExecuteResult(context); ctx.Server.ClearError(); }
protected void Application_Error(object sender, EventArgs e) { HttpContext httpContext = HttpContext.Current; // Для администратора отображаем стандартный вывод ошибки if (httpContext.User != null && httpContext.User.Identity != null && httpContext.User.Identity.IsAuthenticated) { return; } Exception ex = httpContext.Server.GetLastError(); httpContext.Response.Clear(); if (new HttpRequestWrapper(Request).IsAjaxRequest()) { Response.StatusCode = 500; Response.ContentType = "application/json"; Response.Write(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new { errorMessage = ex.Message })); return; } RequestContext requestContext = ((MvcHandler)httpContext.CurrentHandler).RequestContext; IController controller = new HomeController(); var context = new ControllerContext(requestContext, (ControllerBase)controller); ViewResult viewResult = new ViewResult(); HttpException httpException = ex as HttpException; if (httpException != null) { viewResult.ViewBag.HttpCode = httpException.GetHttpCode(); // Исправляем ошибку ELMAH (Request Validation errors does not get logged) // https://code.google.com/p/elmah/issues/detail?id=217 if (httpException is HttpRequestValidationException) { Elmah.ErrorLog.GetDefault(httpContext).Log(new Error(httpException)); } } viewResult.ViewName = "Error"; viewResult.ViewData.Model = new HandleErrorInfo(ex, context.RouteData.GetRequiredString("controller"), context.RouteData.GetRequiredString("action")); viewResult.ExecuteResult(context); httpContext.ClearError(); }
protected void Application_Error(object sender, EventArgs e) { try { HttpContext ctx = HttpContext.Current; Exception ex = ctx.Server.GetLastError(); ctx.Response.Clear(); RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext; IController controller = new HomeController(); // Тут можно использовать любой контроллер, например тот что используется в качестве базового типа var context = new ControllerContext(rc, (ControllerBase)controller); var viewResult = new ViewResult(); var httpException = ex as HttpException; if (httpException != null) { switch (httpException.GetHttpCode()) { case 404: viewResult.ViewName = "Error404"; break; case 401: viewResult.ViewName = "Error401"; break; default: viewResult.ViewName = "Error"; break; } } else { viewResult.ViewName = "Error"; } viewResult.ViewData.Model = new HandleErrorInfo(ex, context.RouteData.GetRequiredString("controller"), context.RouteData.GetRequiredString("action")); viewResult.ExecuteResult(context); ctx.Server.ClearError(); } catch (Exception) { var viewResult = new ViewResult(); viewResult.ViewName = "Error"; //throw; } }
protected override void HandleUnknownAction(string actionName) { var controllerName = (string)RouteData.Values["controller"]; var ex = Server.GetLastError(); var model = new HttpErrorViewModel(ex ?? new HttpException(500, "Something went wrong."), controllerName, actionName); var result = new ViewResult { ViewName = "~/Views/Error/Index.cshtml", ViewData = new ViewDataDictionary<HttpErrorViewModel>(model), }; Response.StatusCode = model.StatusCode; result.ExecuteResult(ControllerContext); }
public void OnException(ExceptionContext filterContext) { HttpContext ctx = HttpContext.Current; Exception ex = ctx.Server.GetLastError(); ctx.Response.Clear(); RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext; IController controller = new HomeController(); // Здесь можно использовать любой контроллер var context = new ControllerContext(rc, (ControllerBase)controller); var viewResult = new ViewResult(); var httpException = ex as HttpException; if (httpException != null) { switch (httpException.GetHttpCode()) { //страницы будут искаться в Views/Shared case 404: viewResult.ViewName = "Error404"; break; case 500: viewResult.ViewName = "Error500"; break; default: viewResult.ViewName = "Error"; break; } } else { viewResult.ViewName = "Error"; } viewResult.ViewBag.Message = filterContext.Exception.Message; //logging HttpSessionStateBase sessionBase = new HttpSessionStateWrapper(ctx.Session); AppLogger.Error(sessionBase, filterContext.Exception.Message); try{ viewResult.ViewBag.TargetSite = filterContext.Exception.TargetSite; viewResult.ViewBag.StackTrace = filterContext.Exception.StackTrace; }catch(Exception e){} viewResult.ExecuteResult(context); ctx.Server.ClearError(); }
public static string CaptureViewOutput(Controller controller, ViewResult view) { var builder = new StringBuilder(); using (var stringWriter = new StringWriter(builder)) { using (var htmlTextWriter = new HtmlTextWriter(stringWriter)) { var currentContext = controller.ControllerContext.HttpContext; try { // get the Request and User objects from the current, unchanged context var currentRequest = HttpContext.Current.ApplicationInstance.Context.Request; var currentUser = HttpContext.Current.ApplicationInstance.Context.User; // create our new HttpResponse object containing our HtmlTextWriter var newResponse = new HttpResponse(htmlTextWriter); // create a new HttpContext object using our new Response object and the existing Request and User objects var newContext = new HttpContextWrapper( new HttpContext(currentRequest, newResponse) { User = currentUser }); // swap in our new HttpContext object - output from this controller is now going to our HtmlTextWriter object controller.ControllerContext.HttpContext = newContext; // Run the ViewResult view.ExecuteResult(controller.ControllerContext); // flush the output newResponse.Flush(); htmlTextWriter.Flush(); stringWriter.Flush(); } finally { // and no matter what happens, set the context back! controller.ControllerContext.HttpContext = currentContext; } } } // our StringBuilder object now contains the output of the ViewResult object return builder.ToString(); }
protected void Application_Error(object sender, EventArgs e) { try { HttpContext ctx = HttpContext.Current; Exception ex = ctx.Server.GetLastError(); ctx.Response.Clear(); if ("System.Web.HttpNotFoundHandler" == ctx.CurrentHandler.GetType().ToString()) { ctx.Server.ClearError(); Response.Redirect("~/Error404"); return; } RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext; ControllerBase controller = new HomeController(); var context = new ControllerContext(rc, controller); var viewResult = new ViewResult(); var httpException = ex as HttpException; if (httpException != null) { int httpCode = httpException.GetHttpCode(); switch (httpCode) { case 404: viewResult.ViewName = "Error404"; break; case 500: viewResult.ViewName = "Error500"; break; default: viewResult.ViewName = "Error"; break; } } else { viewResult.ViewName = "Error"; } viewResult.ViewData.Model = new HandleErrorInfo(ex, context.RouteData.GetRequiredString("controller"), context.RouteData.GetRequiredString("action")); viewResult.ExecuteResult(context); ctx.Server.ClearError(); } catch { return; } }
internal void ExecuteCustomViewResult( ControllerContext controllerContext, int httpCode ) { ViewEngineResult viewLocation = ViewEngines.Engines.FindView( controllerContext, httpCode.ToString( CultureInfo.InvariantCulture ), string.Empty ); if ( viewLocation.View != null ) { ViewResult viewResult = new ViewResult { View = viewLocation.View, ViewData = controllerContext.Controller.ViewData, TempData = controllerContext.Controller.TempData }; viewResult.ExecuteResult( controllerContext ); controllerContext.HttpContext.Response.TrySkipIisCustomErrors = true; } }
protected override void HandleUnknownAction(string actionName) { var name = GetViewName(ControllerContext, string.Format("~/Views/Error/{0}.cshtml", actionName), "~/Views/Error/Error.cshtml", "~/Views/Error/General.cshtml", "~/Views/Shared/Error.cshtml"); var controllerName = (string)RouteData.Values["controller"]; var model = new HandleErrorInfo(Server.GetLastError(), controllerName, actionName); var result = new ViewResult { ViewName = name, ViewData = new ViewDataDictionary<HandleErrorInfo>(model), }; Response.StatusCode = 501; result.ExecuteResult(ControllerContext); }
public override void ExecuteResult(ControllerContext context) { var contentType = context.RequestContext.HttpContext.Request.Headers["Accept"]; if (contentType != null && contentType.Contains("application/json")) { if (Model is IEnumerable && !(Model is string)) { Model = new CollectionWrapper { Collection = (IEnumerable)Model }; } var result = new JsonResult { Data = Model, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; result.ExecuteResult(context); } else { context.Controller.ViewData.Model = Model; var result = new ViewResult { ViewData = context.Controller.ViewData }; result.ExecuteResult(context); } }
public override void ExecuteResult(ControllerContext context) { // Check for JSON or XML in Request.ContentType and serialize data accordingly ViewDataDictionary viewData = context.Controller.ViewData; viewData.Model = Model; // if no JSON or XML result, do default result otherwise just do viewresult if (DefaultResult != null) { DefaultResult.ExecuteResult(context); return; } var result = new ViewResult { ViewData = viewData }; result.ExecuteResult(context); }
public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; var request = context.HttpContext.Request; ViewData["RequestedUrl"] = GetRequestedUrl(request); ViewData["ReferrerUrl"] = GetReferrerUrl(request, request.Url.OriginalString); response.StatusCode = 404; // Prevent IIS7 from overwriting our error page! response.TrySkipIisCustomErrors = true; var viewResult = new ViewResult { ViewName = ViewName, ViewData = ViewData }; response.Clear(); viewResult.ExecuteResult(context); }
/// <summary> /// Render error view /// </summary> /// <param name="ctx">HttpContext</param> /// <param name="view">View name</param> /// <param name="viewData">For ViewData</param> public static void HandleError(this HttpContext ctx, string view, object viewData) { if (ctx == null) throw new ArgumentNullException("ctx"); if (view == null) throw new ArgumentNullException("view"); ctx.Response.Clear(); RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext; string controllerName = rc.RouteData.GetRequiredString("controller"); IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory(); IController controller = factory.CreateController(rc, controllerName); ControllerContext cc = new ControllerContext(rc, (ControllerBase)controller); ViewResult viewResult = new ViewResult { ViewName = view }; if (viewData != null) { foreach (var kv in viewData.ToDictionary()) { viewResult.ViewData.Add(kv.Key, kv.Value); } } viewResult.ExecuteResult(cc); ctx.Server.ClearError(); }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpRequestBase request = context.HttpContext.Request; ControllerBase controller = context.Controller; ViewDataDictionary ViewData = controller.ViewData; ModelStateDictionary modelState = ViewData.ModelState; if (request.IsAjaxRequest()) { JsonProvider provider = JsonProvider.Microsoft; if (controller is ControllerEx) { provider = ((ControllerEx)controller).DefaultJsonProvider; } JsonResultEx jr = new JsonResultEx(provider) { }; if (!modelState.IsValid) { jr.Data = new { Msg = Message, Errors = modelState.GetErrors(), ContainerId = request.Form["formContainerId"], ReloadUrl = ReloadUrl, ReloadOption = (byte)ReloadOption }; } else { jr.Data = new { Msg = Message, ReloadUrl = ReloadUrl, ReloadOption = (byte)ReloadOption }; } jr.ExecuteResult(context); return; } if (ReloadUrl.IsNullOrEmpty() == false && ReloadOption == ReloadAction.Redirect) { HttpResponseBase response = context.HttpContext.Response; response.Redirect(ReloadUrl); return; } ViewData["Message"] = Message; ViewResult vr = new ViewResult() { ViewData = controller.ViewData, ViewName = "Message" }; vr.ExecuteResult(context); }
private bool TryApplyContentType(string acceptType, ControllerContext context) { var response = context.HttpContext.Response; int semi = acceptType.IndexOf(';'); if (semi > 0) acceptType = acceptType.Substring(0, semi); acceptType = acceptType.ToLower(); // Look for specific content types if (acceptType == "application/json") { response.ContentType = "application/json"; using (JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = FormatOutput ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None }) { JsonSerializer serializer = JsonSerializer.Create(); serializer.Serialize(writer, Data); writer.Flush(); } return true; } if (acceptType == "text/xml" || acceptType == "application/xml") { response.ContentType = "text/xml"; if (Data != null) { using (var writer = new XmlTextWriter(response.OutputStream, new UTF8Encoding())) { if (FormatOutput) writer.Formatting = System.Xml.Formatting.Indented; XmlSerializer serializer = new XmlSerializer(Data.GetType()); serializer.Serialize(writer, Data); writer.Flush(); } } return true; } if (!string.IsNullOrEmpty(ViewName) && acceptType == "text/html") { response.ContentType = "text/html"; var viewData = context.Controller.ViewData; viewData.Model = Data; var viewResult = new ViewResult { ViewName = ViewName, MasterName = null, ViewData = viewData, TempData = context.Controller.TempData, ViewEngineCollection = ((Controller) context.Controller).ViewEngineCollection }; viewResult.ExecuteResult(context.Controller.ControllerContext); return true; } if (acceptType == "text/plain") { response.ContentType = "text/plain"; response.Write(Data); return true; } return false; }
/// <summary> /// Display the error view /// </summary> /// <param name="errorPresentation"></param> public static void DisplayErrorView(ErrorPresentation errorPresentation) { // Return the error view ViewResult result = new ViewResult(); result.ViewName = "Error"; result.ViewData = new ViewDataDictionary(errorPresentation); // Set up the breadcrumbs for the view var breadCrumbs = new BreadCrumbs(); breadCrumbs.Add(new BreadCrumb( "Home", "Index", "Home")); breadCrumbs.Add(new BreadCrumb( "Error")); result.ViewData.Add("BreadCrumbs", breadCrumbs); // Get the context for the error controller HttpContext context = HttpContext.Current; if (context.CurrentHandler is MvcHandler) { RequestContext requestContext = ((MvcHandler)context.CurrentHandler).RequestContext; //string controllerName = rc.RouteData.GetRequiredString("Error"); IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory(); IController controller = factory.CreateController(requestContext, "Error"); ControllerContext controllerContext = new ControllerContext(requestContext, (ControllerBase)controller); // Execute the view results result.ExecuteResult(controllerContext); context.Server.ClearError(); } }
private static void Application_Error(object sender, EventArgs e) { var handleServerErrors = ConfigurationManager.AppSettings.Include(ManualServerErrorHandlingMode.ApplicationErrorHandler); var handleNotFoundErrors = ConfigurationManager.AppSettings.Include(ManualNotFoundErrorHandlingMode.ApplicationErrorHandler); if (!handleServerErrors && !handleNotFoundErrors) { return; } // Get the last error. var exception = HttpContext.Current.Server.GetLastError(); if (exception is HttpUnhandledException) { exception = exception.InnerException ?? exception; } var httpException = exception as HttpException; // The exception can be logged here if you want. // Determine if the error should be handled by this module, and if so, how. var statusCode = httpException != null ? httpException.GetHttpCode() : (int) HttpStatusCode.InternalServerError; if (statusCode == (int)HttpStatusCode.NotFound) { if (!handleNotFoundErrors) { return; } } else if (!handleServerErrors) { return; } if (ConfigurationManager.AppSettings.Include(ErrorPageExceptionsMode.HandleInApplicationError)) { // Handle the case where an error page threw an exception; we don't want to loop back to that code. if (HttpContext.Current.Request.Path.StartsWithIgnoreCase("/" + ErrorControllerRouteName + "/")) { HandleErrorHandlingError( "The error handling code threw an exception.", HttpContext.Current.Server.GetLastError()); return; } } try { if (ConfigurationManager.AppSettings.Include(ManualErrorsRenderingMode.ViewResult)) { // ***** The View Result Approach ***** HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.StatusCode = statusCode; if (ConfigurationManager.AppSettings.Include(TrySkipIisCustomErrorsMode.Skip)) { HttpContext.Current.Response.TrySkipIisCustomErrors = true; } var routeData = new RouteData(); routeData.Values.Add("controller", ErrorControllerRouteName); var controllerContext = new ControllerContext( new HttpContextWrapper(HttpContext.Current), routeData, new FakeController()); var viewResult = new ViewResult {ViewName = "ManualErrors"}; viewResult.ViewBag.ExceptionMessage = exception.Message; viewResult.ViewBag.StatusCode = HttpContext.Current.Response.StatusCode; viewResult.ViewBag.SessionData = MvcApplication.GetSessionData(); viewResult.ExecuteResult(controllerContext); HttpContext.Current.Server.ClearError(); } else if (ConfigurationManager.AppSettings.Include(ManualErrorsRenderingMode.ControllerExecute)) { // ***** The Controller Execute Approach ***** var routeData = new RouteData(); routeData.Values.Add("controller", ErrorControllerRouteName); routeData.Values.Add("action", "ManualErrors"); routeData.Values.Add("statusCode", statusCode); var requestContext = new RequestContext(new HttpContextWrapper(HttpContext.Current), routeData); var controllerFactory = ControllerBuilder.Current.GetControllerFactory(); var controller = controllerFactory.CreateController(requestContext, ErrorControllerRouteName); controller.Execute(requestContext); HttpContext.Current.Server.ClearError(); } else if (ConfigurationManager.AppSettings.Include(ManualErrorsRenderingMode.TransferRequest)) { // ***** The TransferRequest Approach ***** // This method of directing back to MVC does not preserve TempData. if (HttpContext.Current.Session != null) { HttpContext.Current.Session["exception"] = exception; } var url = "~/Error/ManualErrors?statusCode=" + statusCode; HttpContext.Current.Server.TransferRequest(url, false, "GET", null); } else if (ConfigurationManager.AppSettings.Include(ManualErrorsRenderingMode.MvcHttpHandler)) { // ***** The MvcHttpHandler Approach ***** var path = HttpContext.Current.Request.Path; HttpContext.Current.RewritePath("~/Error/ManualErrors"); if (HttpContext.Current.Session != null) { HttpContext.Current.Session["statusCode"] = statusCode; } IHttpHandler handler = new MvcHttpHandler(); handler.ProcessRequest(HttpContext.Current); HttpContext.Current.RewritePath(path); HttpContext.Current.Server.ClearError(); } } catch (Exception renderException) { if (ConfigurationManager.AppSettings.Include(ErrorPageExceptionsMode.HandleInApplicationError)) { HandleErrorHandlingError("The MVC manual error handling code threw an exception.", renderException); } else { throw; } } }
public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); HttpResponseBase response = context.HttpContext.Response; HttpRequestBase request = context.HttpContext.Request; // Look for specific content types if (request.AcceptTypes.Contains("text/html")) { response.ContentType = "text/html"; if (!string.IsNullOrEmpty(ViewName)) { var viewData = context.Controller.ViewData; viewData.Model = Data; var viewResult = new ViewResult { ViewName = ViewName, MasterName = null, ViewData = viewData, TempData = context.Controller.TempData, ViewEngineCollection = ((Controller)context.Controller).ViewEngineCollection }; viewResult.ExecuteResult(context.Controller.ControllerContext); } else response.Write(Data); } else if (request.AcceptTypes.Contains("text/plain")) { response.ContentType = "text/plain"; response.Write(Data); } else if (request.AcceptTypes.Contains("application/json")) { using (JsonTextWriter writer = new JsonTextWriter(response.Output)) { var settings = new JsonSerializerSettings(); if (FormatOutput) settings.Formatting = Newtonsoft.Json.Formatting.Indented; JsonSerializer serializer = JsonSerializer.Create(settings); serializer.Serialize(writer, Data); writer.Flush(); } } else if (request.AcceptTypes.Contains("text/xml")) { response.ContentType = "text/xml"; if (Data != null) { using (var writer = new XmlTextWriter(response.OutputStream, new UTF8Encoding())) { if (FormatOutput) writer.Formatting = System.Xml.Formatting.Indented; XmlSerializer serializer = new XmlSerializer(Data.GetType()); serializer.Serialize(writer, Data); writer.Flush(); } } } else { // just write data as a plain string response.Write(Data); } }
protected void Application_Error(object sender, EventArgs e) { //skip error handling if it disabled in config if (GetCustomErrorSection().Mode == CustomErrorsMode.Off) { return; } HttpContext ctx = HttpContext.Current; //Exception ex = ctx.Server.GetLastError(); ctx.Response.Clear(); ControllerContext context; var controller = new TwitterController(); // here we can use any controller var handler = ctx.CurrentHandler as MvcHandler; if (handler == null) { //in case of FileNotFound or other handlers var routeData = new RouteData(); routeData.Values.Add("controller", "twitter"); context = new ControllerContext(new RequestContext(new HttpContextWrapper(Context), routeData), new TwitterController()); } else { context = new ControllerContext(handler.RequestContext, controller); } var viewResult = new ViewResult {ViewName = "Error"}; viewResult.ExecuteResult(context); ctx.Server.ClearError(); }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpRequestBase request = context.HttpContext.Request; ControllerBase controller = context.Controller; ViewDataDictionary ViewData = controller.ViewData; ModelStateDictionary modelState = ViewData.ModelState; if (request.IsAjaxRequest()) { JsonProvider provider = JsonProvider.Microsoft; if (controller is ControllerEx) { provider = ((ControllerEx)controller).DefaultJsonProvider; } JsonResultEx jr = new JsonResultEx(provider) { }; if (!modelState.IsValid) { jr.Data = new { Msg = Message, Errors = modelState.GetErrors(), ContainerId = request.Form["formContainerId"], ReloadUrl = ReloadUrl, ReloadOption = (byte)ReloadOption }; } else { jr.Data = new { Msg = Message, ReloadUrl = ReloadUrl, ReloadOption = (byte)ReloadOption }; } jr.ExecuteResult(context); return; } if (ReloadUrl.IsNullOrEmpty() == false && ReloadOption == ReloadAction.Redirect) { HttpResponseBase response = context.HttpContext.Response; response.Redirect(ReloadUrl); return; } ViewData["Message"] = Message; ViewResult vr = new ViewResult() { ViewData = controller.ViewData, ViewName = "Message" }; vr.ExecuteResult(context); }
protected void Application_Error() { HttpContext ctx = HttpContext.Current; Exception ex = ctx.Server.GetLastError(); ctx.Response.Clear(); RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext; BaseLogonController controller = new ErrorController(); var context = new ControllerContext(rc, (ControllerBase)controller); var viewResult = new ViewResult(); var httpException = ex as HttpException; if (httpException != null) { switch (httpException.GetHttpCode()) { case 403: viewResult.ViewName = "Http403"; break; case 404: viewResult.ViewName = "Http404"; break; default: viewResult.ViewName = "General"; break; } } else { viewResult.ViewName = "General"; } viewResult.ViewData.Model = new HandleErrorInfo(ex, context.RouteData.GetRequiredString("controller"), context.RouteData.GetRequiredString("action")); viewResult.ViewData["AccountID"] = controller.CurrentAccountID; viewResult.ExecuteResult(context); ctx.Server.ClearError(); }