public override void OnException(ExceptionContext filterContext) { StringBuilder routeValues = new StringBuilder(); foreach (var val in filterContext.RouteData.Values) { routeValues.AppendFormat(@"({0}:{1})/", val.Key, val.Value); } string url = "NULL"; if (filterContext.HttpContext.Request.Url != null) { url = filterContext.HttpContext.Request.Url.ToString(); } System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~/"); CustomErrorsSection errorsSection = (CustomErrorsSection)config.GetSection("system.web/customErrors"); if (errorsSection.Mode == CustomErrorsMode.On || (errorsSection.Mode == CustomErrorsMode.RemoteOnly && !HttpContext.Current.Request.IsLocal)) { filterContext.ExceptionHandled = true; SingalElmah(filterContext); filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Error", action = "Index" })); } else { base.OnException(filterContext); SingalElmah(filterContext); } }
private void Context_Error(object sender, EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; int statusCode = ((HttpException)context.Error).GetHttpCode(); if ((object.ReferenceEquals(context.Error.GetType(), typeof(HttpException))) && (statusCode == 404 || statusCode == 500)) { // Get the Web application configuration. System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~/web.config"); // Get the section. CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors"); // Get the collection CustomErrorCollection customErrorsCollection = customErrorsSection.Errors; //Clears existing response headers and sets the desired ones. context.Response.ClearHeaders(); context.Response.StatusCode = statusCode; if ((customErrorsCollection.Get(statusCode.ToString()) != null)) { context.Server.Transfer(customErrorsCollection.Get(statusCode.ToString()).Redirect); } else { context.Response.Flush(); } } }
/// <summary> /// Redirects the client browser based on the specified <paramref name="httpStatusCode"/> /// </summary> /// <param name="httpStatusCode"><see cref="HttpStatusCode"/> to be used for the redirect.</param> protected virtual void Redirect(HttpStatusCode httpStatusCode) { int statusCode = (int)httpStatusCode; if (m_application.Context.IsCustomErrorEnabled) { // Defer redirect to customErrors settings in the config file to allow for custom error pages. ConfigurationFile configFile = ConfigurationFile.Current; CustomErrorsSection customErrors = configFile.Configuration.GetSection("system.web/customErrors") as CustomErrorsSection; if (customErrors != null && customErrors.Errors[statusCode.ToString()] != null) { // Set status code for the response. m_application.Context.Response.StatusCode = statusCode; // Throw exception for ASP.NET pipeline to takeover processing. throw new HttpException(statusCode, string.Format("Security exception (HTTP status code: {0})", statusCode)); } } // Abruptly ending the processing caused by a redirect does not work well when processing static content. string redirectUrl = string.Format("~/SecurityPortal.aspx?s={0}&r={1}", statusCode, HttpUtility.UrlEncode(VirtualPathUtility.ToAppRelative(m_application.Request.Url.PathAndQuery))); if (m_application.Context.Handler is DefaultHttpHandler) { // Accessed resource is static. m_application.Context.Response.Redirect(redirectUrl, false); } else { // Accessed resource is dynamic. m_application.Context.Response.Redirect(redirectUrl, true); } }
public string GenerateOutput(HttpContext context, Config c) { StringBuilder sb = new StringBuilder(); //Figure out CustomErrorsMode System.Configuration.Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null); CustomErrorsSection section = (configuration != null) ? section = (CustomErrorsSection)configuration.GetSection("system.web/customErrors") : null; CustomErrorsMode mode = (section != null) ? section.Mode : CustomErrorsMode.RemoteOnly; //What is diagnostics enableFor set to? DiagnosticMode dmode = c.get <DiagnosticMode>("diagnostics.enableFor", DiagnosticMode.None); //Is it set all all? bool diagDefined = (c.get("diagnostics.enableFor", null) != null); //Is it available from localhost. bool availLocally = (!diagDefined && mode == CustomErrorsMode.RemoteOnly) || (dmode == DiagnosticMode.Localhost); sb.AppendLine("The Resizer diagnostics page is " + (availLocally ? "only available from localhost." : "disabled.")); sb.AppendLine(); if (diagDefined) { sb.AppendLine("This is because <diagnostics enableFor=\"" + dmode.ToString() + "\" />."); } else { sb.AppendLine("This is because <customErrors mode=\"" + mode.ToString() + "\" />."); } sb.AppendLine(); sb.AppendLine("To override for localhost access, add <diagnostics enableFor=\"localhost\" /> in the <resizer> section of Web.config."); sb.AppendLine(); sb.AppendLine("To ovveride for remote access, add <diagnostics enableFor=\"allhosts\" /> in the <resizer> section of Web.config."); sb.AppendLine(); return(sb.ToString()); }
private ConfigurationCustomErrorsModel ProcessCustomErrors(CustomErrorsSection customErrorsSection) { if (customErrorsSection == null) { return(null); } var result = new ConfigurationCustomErrorsModel { DefaultRedirect = customErrorsSection.DefaultRedirect, RedirectMode = customErrorsSection.RedirectMode.ToString(), Mode = customErrorsSection.Mode.ToString() }; var errorsSection = customErrorsSection.Errors; if (errorsSection != null) { var resultErrors = new List <ConfigurationCustomErrorsErrorModel>(); foreach (CustomError error in errorsSection) { var resultError = new ConfigurationCustomErrorsErrorModel { Redirect = error.Redirect, StatusCode = error.StatusCode }; resultErrors.Add(resultError); } result.Errors = resultErrors; } return(result); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { string err = Resources.GenericError; Configuration conf = WebConfigurationManager.OpenWebConfiguration(Context.Request.Path); CustomErrorsSection ces = (CustomErrorsSection)conf.GetSection("system.web/customErrors"); if (ces != null && !_overrideConfig) { switch (ces.Mode) { case CustomErrorsMode.Off: err = _errorText; break; case CustomErrorsMode.On: //Display generic error break; case CustomErrorsMode.RemoteOnly: if (Context.Request.IsLocal) { err = _errorText; } break; } } else { //OverrideConfig: Display detailed error message err = _errorText; } BodyPanel.Controls.Add(new LiteralControl(err)); }
public virtual void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); if (ex.InnerException != null) { //Exception baseEx = Server.GetLastError().GetBaseException(); //CSCore.CSLogger.Instance.LogException(baseEx.Message, baseEx); CSCore.CSLogger.Instance.LogException(ex.InnerException.Message, ex.InnerException); } HttpException httpEx = ex as HttpException; // show "redirect" message is file does not exist. if (httpEx != null) { if (httpEx.GetHttpCode() == 404) { Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/"); CustomErrorsSection customErrors = (CustomErrorsSection)configuration.GetSection("system.web/customErrors"); if (string.IsNullOrEmpty(customErrors.Errors["404"].Redirect)) // ... no redirect page specified in code { } } } }
void context_Error(object sender, System.EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; HttpException exception = context.Error as HttpException; if (exception != null) { // Get error information int statusCode = exception.GetHttpCode(); // Update the response with the correct status code context.Response.ClearHeaders(); context.Response.ClearContent(); context.Response.StatusCode = statusCode; // Read configuration CustomErrorsSection customErrorsSection = (CustomErrorsSection)ConfigurationManager.GetSection("system.web/customErrors"); CustomError customError = customErrorsSection.Errors[context.Response.StatusCode.ToString()]; string errorPageUrl = (customError == null) ? null : customError.Redirect; if (string.IsNullOrEmpty(errorPageUrl)) { errorPageUrl = customErrorsSection.DefaultRedirect; } // Handle the request if (!string.IsNullOrEmpty(errorPageUrl)) { context.Server.Transfer(errorPageUrl); } else { context.Response.Flush(); } } }
public static string RedirectCustomErrorsView() { Configuration config = null; CustomErrorsSection section = null; string path = string.Empty; try { config = WebConfigurationManager.OpenWebConfiguration("~"); section = (CustomErrorsSection)config.GetSection("system.web/customErrors"); if (section?.Errors != null && section.Errors.Count > 0) { for (var i = 0; i < section.Errors.Count; i++) { if (section.Errors[i].StatusCode == 500) { path = section.Errors[i].Redirect ?? string.Empty; break; } } } else if (section != null && section.DefaultRedirect != null) { path = section.DefaultRedirect; } } finally { config = null; section = null; } return(path); }
public void Init(HttpApplication application) { System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~"); CustomErrors = (CustomErrorsSection)configuration.GetSection("system.web/customErrors"); application.EndRequest += Application_EndRequest; }
/// <summary> /// Redirect to 404 page /// </summary> public static void RedirectToErrorPage() { System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~"); CustomErrorsSection section = (CustomErrorsSection)configuration.GetSection("system.web/customErrors"); HttpContext.Current.Response.Redirect(section.Errors["404"].Redirect); }
/// <summary> /// GetErrorPage reads custom errors pages section from web.config and gets the default error page url /// </summary> /// <returns></returns> public static string GetErrorPage() { System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~"); CustomErrorsSection section = (CustomErrorsSection)configuration.GetSection("system.web/customErrors"); return(section.DefaultRedirect.ToString()); }
private static CustomErrorsMode CompilationDebug() { string currentExecutionFilePath = HttpContext.Current.Request.CurrentExecutionFilePath; CustomErrorsSection section = WebConfigurationManager.OpenWebConfiguration(currentExecutionFilePath.Substring(0, currentExecutionFilePath.LastIndexOf("/", StringComparison.CurrentCultureIgnoreCase))).GetSection("system.web/customErrors") as CustomErrorsSection; return(section.Mode); }
// Token: 0x0600002D RID: 45 RVA: 0x00004C98 File Offset: 0x00002E98 protected override void View() { this.sysconfiginfo = SysConfigs.GetConfig(); this.sitelist = SiteBll.GetSiteList(); Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~"); if (configuration.AppSettings.Settings["sitepath"] != null) { this.mainsite = configuration.AppSettings.Settings["sitepath"].Value; } CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors"); if (customErrorsSection.Mode == CustomErrorsMode.Off) { this.customerror = 1; } this.adminsiteconfig = SiteConfigs.LoadConfig(FPUtils.GetMapPath(this.webpath + this.sysconfiginfo.adminpath + "/site.config")); if (this.ispost) { if (!this.isperm) { this.ShowErr("对不起,您没有限权进行修改配置。"); return; } this.sysconfiginfo = FPRequest.GetModel <SysConfig>(this.sysconfiginfo); if (this.sysconfiginfo.admintitle == "") { this.sysconfiginfo.admintitle = this.adminsiteconfig.sitetitle; } this.sysconfiginfo.passwordkey = WMSUtils.CreateAuthStr(10); WMSCookie.WriteCookie("password", DES.Encode(this.user.password, this.sysconfiginfo.passwordkey)); SysConfigs.SaveConfig(this.sysconfiginfo); SysConfigs.ResetConfig(); if (FPRequest.GetInt("customerror") != this.customerror) { this.customerror = FPRequest.GetInt("customerror"); if (this.customerror == 1) { customErrorsSection.Mode = CustomErrorsMode.Off; } else { customErrorsSection.Mode = CustomErrorsMode.RemoteOnly; } } if (configuration.AppSettings.Settings["sitepath"] != null) { configuration.AppSettings.Settings["sitepath"].Value = FPRequest.GetString("mainsite"); } else { configuration.AppSettings.Settings.Add("sitepath", FPRequest.GetString("mainsite")); } configuration.Save(ConfigurationSaveMode.Modified); WebConfig.ReSet(); base.AddMsg("更新配置成功!"); } base.SaveRightURL(); }
public void Init(HttpApplication application) { var configuration = WebConfigurationManager.OpenWebConfiguration("~"); this.customErrors = (CustomErrorsSection)configuration.GetSection("system.web/customErrors"); application.Error += this.OnError; }
public void Defaults() { CustomErrorsSection c = new CustomErrorsSection(); Assert.IsNull(c.DefaultRedirect, "A1"); Assert.IsNotNull(c.Errors, "A2"); Assert.AreEqual(CustomErrorsMode.RemoteOnly, c.Mode, "A3"); }
/// <summary> /// 把错误信息发送并跳转到错误页面 /// </summary> /// <param name="ex">异常</param> public static void GoToErrURLAndSendErrMsg(string ex) { CustomErrorsSection cs = EnvironmentHelper.GetCustomErrorSection(); string url = EnvironmentHelper.GetCustomErrorURL(cs); //System.Web.HttpContext.Current.Application["errmsginfo"] = ex; System.Web.HttpContext.Current.Response.Redirect("ErrTest.aspx?errmsginfo=" + ex); }
public static void Main() { // <Snippet1> // Get the Web application configuration. Configuration configuration = WebConfigurationManager.OpenWebConfiguration( "/aspnetTest"); // Get the section. CustomErrorsSection customErrors = (CustomErrorsSection)configuration.GetSection( "system.web/customErrors"); // Get the collection. CustomErrorCollection customErrorsCollection = customErrors.Errors; // </Snippet1> // <Snippet2> // Create a new error object. // Does not exist anymore. // CustomError newcustomError = new CustomError(); // </Snippet2> // <Snippet3> // Create a new error object. CustomError newcustomError2 = new CustomError(404, "customerror404.htm"); // </Snippet3> // <Snippet4> // Get first errorr Redirect. CustomError currentError0 = customErrorsCollection[0]; string currentRedirect = currentError0.Redirect; // Set first error Redirect. currentError0.Redirect = "customError404.htm"; // </Snippet4> // <Snippet5> // Get second error StatusCode. CustomError currentError1 = customErrorsCollection[1]; int currentStatusCode = currentError1.StatusCode; // Set the second error StatusCode. currentError1.StatusCode = 404; // </Snippet5> }
private void Context_Error(object sender, EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; // determine if it was an HttpException if ((object.ReferenceEquals(context.Error.GetType(), typeof(HttpException)))) { // Get the Web application configuration. System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~/web.config"); // Get the section. CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors"); // Get the collection CustomErrorCollection customErrorsCollection = customErrorsSection.Errors; int statusCode = ((HttpException)context.Error).GetHttpCode(); //Clears existing response headers and sets the desired ones. context.Response.ClearHeaders(); context.Response.StatusCode = statusCode; if (statusCode == 404) { string Path = context.Request.Path; if (Path.Contains("playlist.xml")) { context.Response.Clear(); context.Response.StatusCode = 101; context.Response.Redirect("/mp3/playlist.xml"); } else if (!Path.EndsWith(".js") && !Path.EndsWith(".gif") && !Path.EndsWith(".jpg") && !Path.EndsWith(".png")) { context.Response.Clear(); context.Response.Write("404 file not found"); context.Response.Redirect("/404.aspx"); } } else { } //context.Response.Flush(); } else { // log the error here in the tracer //Clears existing response headers and sets the desired ones. context.Response.ClearHeaders(); context.Response.StatusCode = 500; //context.Server.Transfer("/500.aspx"); if (!context.Request.IsLocal) { context.Response.Redirect("/500.aspx"); } // } }
private void Configure() { CustomErrorsSection section = new CustomErrorsSection { DefaultRedirect = "~/ErrorPages/Generic.aspx", Mode = CustomErrorsMode.On }; section.Errors.Add(new CustomError(403, "~/ErrorPages/AccessDenied.aspx")); section.Errors.Add(new CustomError(404, "~/ErrorPages/NotFound.aspx")); configurationManager.Expect(m => m.GetSection <CustomErrorsSection>(It.IsAny <string>())).Returns(section); }
public override CheckResult PerformCheck() { CustomErrorsSection configSection = (CustomErrorsSection)ConfigurationManager.GetSection("system.web/customErrors"); if (configSection.Mode == CustomErrorsMode.Off) { return(CreateCheckResult(HealthStatusType.Warning, "Custom errors are off. You should never have them off in production.")); } return(CreateCheckResult(statusText: $"Custom errors are {configSection.Mode.ToString()}")); }
/// <summary> /// Process /// </summary> /// <param name="context"></param> public static void Process(HttpContext context) { int code = context.Response.StatusCode; if (code == 200 || code == 301 || code == 302) { return; } CustomErrorsSection customErrors = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection; if (customErrors.Mode == CustomErrorsMode.On || (customErrors.Mode == CustomErrorsMode.RemoteOnly && IsRemote(context))) { string html = ""; string path = ""; foreach (CustomError item in customErrors.Errors) { if (item.StatusCode == context.Response.StatusCode) { path = item.Redirect; break; } } if (string.IsNullOrEmpty(path)) { path = customErrors.DefaultRedirect; } string path1 = context.Server.MapPath(path); if (File.Exists(path1)) { using (FileStream fs = File.Open(path1, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { StreamReader sr = new StreamReader(fs); html = sr.ReadToEnd(); } } else { html = DefaultErrorHtml; } context.Response.ClearContent(); context.Response.Clear(); context.Response.StatusCode = code; context.Response.Write(html); context.Response.End(); } }
public override void OnError(HttpContextBase context) { Exception e = context.Server.GetLastError().GetBaseException(); HttpException httpException = e as HttpException; int statusCode = (int)HttpStatusCode.InternalServerError; // Skip Page Not Found and Service not unavailable from logging if (httpException != null) { statusCode = httpException.GetHttpCode(); if ((statusCode != (int)HttpStatusCode.NotFound) && (statusCode != (int)HttpStatusCode.ServiceUnavailable)) { Log.Exception(e); } } string redirectUrl = null; if (context.IsCustomErrorEnabled) { CustomErrorsSection section = IoC.Resolve <IConfigurationManager>().GetSection <CustomErrorsSection>("system.web/customErrors"); if (section != null) { redirectUrl = section.DefaultRedirect; if (httpException != null) { if (section.Errors.Count > 0) { CustomError item = section.Errors[statusCode.ToString(Constants.CurrentCulture)]; if (item != null) { redirectUrl = item.Redirect; } } } } } context.Response.Clear(); context.Response.StatusCode = statusCode; context.Response.TrySkipIisCustomErrors = true; context.ClearError(); if (!string.IsNullOrEmpty(redirectUrl)) { context.Server.Transfer(redirectUrl); } }
protected override void OnSystemUpgrading(HttpContext context, string html = null, string scriptUrl = null) { CustomErrorsSection customErrorsSection = (CustomErrorsSection)ConfigurationManager.GetSection("system.web/customErrors"); if (customErrorsSection.Mode.Equals(CustomErrorsMode.Off) || (customErrorsSection.Mode.Equals(CustomErrorsMode.RemoteOnly) && HttpContext.Current.Request.IsLocal)) { base.OnSystemUpgrading(context, html, scriptUrl); } else { DisplayPage(context, SystemRestartingOrUpgradingHtml); } }
private string GetCustomError(string statusCode) { CustomErrorsSection customErrorsSection = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection; if (customErrorsSection != null) { CustomError customErrorPage = customErrorsSection.Errors[statusCode]; if (customErrorPage != null) { return(customErrorPage.Redirect); } } return(null); }
/// <summary> /// Converts from. /// </summary> /// <param name="customErrorsSection">The custom errors section.</param> /// <returns></returns> public static SiteErrors ConvertFrom(CustomErrorsSection customErrorsSection) { var customErrors = new SiteErrors { DefaultUrl = customErrorsSection.DefaultRedirect }; foreach (var key in customErrorsSection.Errors.AllKeys) { customErrors.Errors.Add(new Error { StatusCode = key, Url = customErrorsSection.Errors.Get(key).Redirect }); } return(customErrors); }
static string GetCustomError(string code) { CustomErrorsSection section = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection; if (section != null) { CustomError page = section.Errors[code]; if (page != null) { return(page.Redirect); } } return(section.DefaultRedirect); }
/// <summary> /// 根据CustomeErrors配置获取错误处理页面URL /// </summary> /// <param name="customErrorsSection">错误配置节</param> /// <returns>错误处理页面URL</returns> public static string GetCustomErrorURL(CustomErrorsSection customErrorsSection) { string redirectURL = string.Empty; if (customErrorsSection.Mode == CustomErrorsMode.On || (customErrorsSection.Mode == CustomErrorsMode.RemoteOnly && !HttpContext.Current.Request.IsLocal)) { redirectURL = customErrorsSection.DefaultRedirect; CustomError error = customErrorsSection.Errors[Convert.ToString(HttpContext.Current.Response.StatusCode)]; if (null != error) { redirectURL = error.Redirect; } } return(redirectURL); }
static CustomErrors() { _errors = new Hashtable(); CustomErrorsSection section = (CustomErrorsSection)WebConfigurationManager.GetSection("system.web/customErrors"); _mode = section.Mode; _redirectMode = section.RedirectMode; _defaultRedirect = section.DefaultRedirect; foreach (CustomError e in section.Errors) { if (!string.IsNullOrEmpty(e.Redirect)) { _errors.Add(e.StatusCode, e.Redirect); } } _ips = Dns.GetHostAddresses("localhost"); }
private static Func <IHttpHandler> FindHttpHandler(CustomErrorsSection customErrorsSection, string customErrorId) { var customErrorsSectionSyn = new CustomErrorsSectionSyn(customErrorsSection); var customErrorSyn = new CustomErrorSyn(customErrorsSection.Errors[customErrorId]); Type httpHandlerType = null; try { httpHandlerType = customErrorsSectionSyn.DefaultUrlRoutingType; if (customErrorSyn.UrlRoutingType != null) { httpHandlerType = customErrorSyn.UrlRoutingType; } } catch { } return(httpHandlerType == null ? (Func <IHttpHandler>)null : () => (IHttpHandler)Activator.CreateInstance(httpHandlerType)); }