当前位置: 首页>>代码示例>>C#>>正文


C# HttpException.GetHttpCode方法代码示例

本文整理汇总了C#中System.Web.HttpException.GetHttpCode方法的典型用法代码示例。如果您正苦于以下问题:C# HttpException.GetHttpCode方法的具体用法?C# HttpException.GetHttpCode怎么用?C# HttpException.GetHttpCode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Web.HttpException的用法示例。


在下文中一共展示了HttpException.GetHttpCode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: HandleException

        public static void HandleException(this ExceptionContext filterContext)
        {
            var ex = filterContext.Exception;
            var contextResponse = filterContext.HttpContext.Response;

            LogException(ex);

            HttpException httpException = new HttpException(null, ex);
            int httpExceptionCode = httpException.GetHttpCode();

            string controllerName = (string)filterContext.RouteData.Values["controller"];
            string actionName = (string)filterContext.RouteData.Values["action"];
            HandleErrorInfo model = new HandleErrorInfo(ex, controllerName ?? "Unknown", actionName ?? "Unknown");
            ViewResult result = new ViewResult
            {
                ViewName = "Error",
                MasterName = "_Layout",
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData
            };
            
            filterContext.Result = result;
            filterContext.ExceptionHandled = true;
            contextResponse.Clear();
            contextResponse.StatusCode = httpExceptionCode;
            contextResponse.TrySkipIisCustomErrors = true;
        }
开发者ID:garysharp,项目名称:Disco,代码行数:27,代码来源:HelperExtensions.cs

示例2: ApplicationOnErrorFilter

        /// <summary>
        /// Handles the Error event of the Application control.
        /// </summary>
        /// <param name="httpapplication">The http application.</param>
        /// <param name="httpexception">The http exception.</param>
        private static void ApplicationOnErrorFilter(HttpApplication httpapplication, HttpException httpexception)
        {
            // Modify if need
            try
            {
                if (httpexception != null)
                {
                    switch ((HttpStatusCode)httpexception.GetHttpCode())
                    {
                        case HttpStatusCode.InternalServerError:
                            // Error caused by Search engine caching of ASP.NET assembly WebResource.axd file(s)
                            // 'WebResource.axd' Or 'ScriptResource.axd'
                            string url = httpapplication.Context.Request.Url.AbsolutePath;
                            if (url.EndsWith(".axd", StringComparison.OrdinalIgnoreCase))
                            {
                                httpapplication.Context.Server.ClearError();
                            }

                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                // CRITICAL: Error Log must not throw unhandled errors
                Logger.InfoException(ex.Message, ex);
            }
        }
开发者ID:MGramolini,项目名称:vodca,代码行数:33,代码来源:VLog.OnErrorrFilter.cs

示例3: Application_Error

        protected void Application_Error()
        {
            if (HttpContext.Current == null)
            {
                // errors in Application_Start will end up here

                return;
            }

            if (HttpContext.Current.IsCustomErrorEnabled)
            {
                return;
            }
            var exception = Server.GetLastError();

            var httpException = new HttpException(null, exception);
            if (httpException.GetHttpCode() == 404 && WebHelper.IsStaticResource(this.Request))
            {
                return;
            }

            //TODO: 记录Log(忽略404,403)
            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Index");
            routeData.Values.Add("httpException", httpException);

            Server.ClearError();

            // Call target Controller and pass the routeData.
            //Ref nop&nblog
            IController errorController = SDFEngine.Container.Resolve<ErrorController>();

            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
开发者ID:sdf333,项目名称:MVCDEMO,代码行数:35,代码来源:Global.asax.cs

示例4: Application_Error

		protected void Application_Error()
		{
			// Log ASP.NET errors (404, 500)
			HttpException exception = new HttpException(null, HttpContext.Current.Server.GetLastError());
			Log.Error("An ASP.NET based error occurred - ({0}) - {1}", 
						exception.GetHttpCode(),
						exception.ToString());
		}
开发者ID:35e8,项目名称:roadkill,代码行数:8,代码来源:RoadkillApplication.cs

示例5: GetErrorRouteData

        private RouteData GetErrorRouteData(HttpException httpException, CustomErrorsSection config)
        {
            var statusCode = httpException.GetHttpCode().ToString(CultureInfo.InvariantCulture);

            var routeData = RouteInfo.GetRouteDataByUrl(config.Errors[statusCode] != null
                                             ? config.Errors[statusCode].Redirect
                                             : config.DefaultRedirect);

            return routeData;
        }
开发者ID:gabykotliar,项目名称:ScrumBoard,代码行数:10,代码来源:Global.asax.cs

示例6: Increment_WithHttpExceptionThatIsNot404_AddsStatusCodeToReadingName

        public void Increment_WithHttpExceptionThatIsNot404_AddsStatusCodeToReadingName()
        {
            var sensor = new ExceptionSensor();

            var exception = new HttpException(500, "Page not found");
            sensor.AddError(exception);

            Reading reading = null;
            ReadingPublisher.Readings.TryDequeue(out reading); // TotalExceptions
            ReadingPublisher.Readings.TryDequeue(out reading);

            Assert.That(reading.Data.Name, Is.EqualTo(exception.GetHttpCode() + exception.GetType().Name ));
        }
开发者ID:aqueduct,项目名称:Aqueduct.Monitoring,代码行数:13,代码来源:ExceptionSensorTests.cs

示例7: Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            ex = (HttpException)Server.GetLastError();
            int httpCode = ex.GetHttpCode();

            // Filter for Error Codes and set text

            if (httpCode == 401)
                ex = new HttpException
                    (httpCode, "Request Unauthorized!", ex);
            else
            if (httpCode == 403)
                ex = new HttpException
                    (httpCode, "Forbidden Request!",ex);
            else
            if (httpCode >= 400 && httpCode < 500)
                ex = new HttpException
                    (httpCode, "File not found!", ex);
            else
            if (httpCode > 499)
                ex = new HttpException
                    (ex.ErrorCode, "Oops...! :(", ex);
            else
                ex = new HttpException
                    (httpCode, "Unexpected Exception!", ex);

            // Log the exception and notify system operators
            ExceptionUtility.LogException(ex, "HttpErrorPage");
            ExceptionUtility.NotifySystemOps(ex);

            // Fill the page fields
            exCode.Text = httpCode.ToString();
            exMessage.Text = ex.Message;
            exTrace.Text = ex.StackTrace;


            // Show Inner Exception fields for local access
            if (ex.InnerException != null)
            {
                innerTrace.Text = ex.InnerException.StackTrace;
                InnerErrorPanel.Visible = Request.IsLocal;
                innerMessage.Text = string.Format("HTTP {0}: {1}",
                  httpCode, ex.InnerException.Message);
            }
            // Show Trace for local access
            exTrace.Visible = Request.IsLocal;

            // Clear the error from the server
            Server.ClearError();
        }
开发者ID:Pay-it-Forward-Telerik-Academy,项目名称:PayItForward,代码行数:50,代码来源:HttpErrorPage.aspx.cs

示例8: ShouldHandle

        private bool ShouldHandle(ExceptionContext filterContext)
        {
            if (filterContext.IsChildAction)
            {
                return false;
            }

            if (filterContext.ExceptionHandled)
            {
                return false;
            }

            var exception = filterContext.Exception;

            var httpException = new HttpException(null, exception);
            var httpExceptionHttpCode = httpException.GetHttpCode();
            if (httpExceptionHttpCode != 500)
            {
                return false;
            }

            return this.ExceptionType.IsInstanceOfType(exception);
        }
开发者ID:sebnilsson,项目名称:WikiDown,代码行数:23,代码来源:HandleExceptionsAttribute.cs

示例9: Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            ex = (HttpException)Server.GetLastError();
            int httpCode = ex.GetHttpCode();

            // Filter for Error Codes and set text
            if (httpCode >= 400 && httpCode < 500)
                ex = new HttpException
                    (httpCode, "Safe message for 4xx HTTP codes.", ex);
            else if (httpCode > 499)
                ex = new HttpException
                    (ex.ErrorCode, "Safe message for 5xx HTTP codes.", ex);
            else
                ex = new HttpException
                    (httpCode, "Safe message for unexpected HTTP codes.", ex);

            // Log the exception and notify system operators
            ISTATRegistry.Classes.ExceptionUtility.LogException(ex, "HttpErrorPage");
            //ExceptionUtility.NotifySystemOps(ex);

            // Fill the page fields
            exMessage.Text = ex.Message;
            exTrace.Text = ex.StackTrace;

            // Show Inner Exception fields for local access
            if (ex.InnerException != null)
            {
                innerTrace.Text = ex.InnerException.StackTrace;
                InnerErrorPanel.Visible = true;
                innerMessage.Text = string.Format("HTTP {0}: {1}",
                  httpCode, ex.InnerException.Message);
            }

            // Clear the error from the server
            Server.ClearError();
        }
开发者ID:alcardac,项目名称:SDMX_ART_REPO,代码行数:36,代码来源:HttpErrorPage.aspx.cs

示例10: ResourceErrorActionResult

 /// <summary>
 /// Sends back a response using the status code in the HttpException.
 /// The response body contains a details serialized in the responseFormat.
 /// If the HttpException.Data has a key named "details", its value is used as the response body.
 /// If there is no such key, HttpException.ToString() is used as the response body.
 /// </summary>
 /// <param name="httpException"></param>
 /// <param name="responseFormat"></param>
 public ResourceErrorActionResult(HttpException httpException, ContentType responseFormat) {
     this.statusCode = (HttpStatusCode)httpException.GetHttpCode();
     this.details = httpException.Data.Contains("details") ? httpException.Data["details"] : httpException.ToString();
     this.responseFormat = responseFormat;
 }
开发者ID:jesshaw,项目名称:ASP.NET-Mvc-3,代码行数:13,代码来源:ResourceErrorActionResult.cs

示例11: OnException

        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.IsChildAction)
            {
                return;
            }

            //NOTE: I used to check for custom errors enabled but then realized that we 'never' really 
            // want to see a YSOD instead of being redirected to the installer or the not authorized page.
            //if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            //    return;
            if (filterContext.ExceptionHandled)
                return;

            var exception = filterContext.Exception;
            var httpException = new HttpException(null, exception);

            if (httpException.GetHttpCode() != (int)global::System.Net.HttpStatusCode.Forbidden
                && httpException.GetHttpCode() != (int)global::System.Net.HttpStatusCode.Unauthorized)
            {
                //ignore if not 403 or 401
                return;
            }
            
            switch (httpException.GetHttpCode())
            {
                case (int)global::System.Net.HttpStatusCode.Unauthorized:
                    //The user could not login                     

                    object routeVals;
                    if (_showLoginOverlay)
                    {
                        routeVals = new
                            {
                                area = "Umbraco",
                                action = "Login",
                                controller = "Default",
                                ReturnUrl = filterContext.HttpContext.Request.Url.PathAndQuery,
                                displayType = LoginDisplayType.ShowOverlay
                            };
                    }
                    else
                    {
                        //since we're not displaying the overlay, we wont include the other route val, makes urls nicer
                        routeVals = new
                            {
                                area = "Umbraco",
                                action = "Login",
                                controller = "Default",
                                ReturnUrl = filterContext.HttpContext.Request.Url.PathAndQuery
                            };
                    }

                    //redirect to login
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(routeVals));

                    break;
                case (int)global::System.Net.HttpStatusCode.Forbidden:
                    //The user does not have access to the resource, show the insufficient priviledges view

                    //need to update the route values so that Login returns the correct view
                    var defaultController = new DefaultController(BackOfficeRequestContext);
                    filterContext.RouteData.Values["Action"] = "InsufficientPermissions";
                    filterContext.RouteData.Values["Controller"] = "Default";
                    filterContext.HttpContext.Response.StatusCode = (int)global::System.Net.HttpStatusCode.Forbidden;
                    filterContext.Result = defaultController.InsufficientPermissions(filterContext.HttpContext.Request.Url.PathAndQuery);
                    break;
            }
            
            filterContext.ExceptionHandled = true;
            //NOTE: Due to the way the FormsAuthenticationModule in ASP.Net works, specifically in it's OnLeave method
            // it specifically checks for a 401 status code, changes it to a 301 and redirects to the FormsAuthentication.LoginUrl
            // which can only be set singly meaning that you can't have 2 different login URLs even when using the 'location' 
            // element in your web.config. Hopefully MS fixes this in future versions of .Net. In the meantime we have 2 options:
            // - Don't return a 401 Http status code
            // - Hijack the Application_EndRequest to detect that we wanted to render a 401 and change it to 401 which is kinda ugly.
            //   so, we're just not going to return a 401 status code.
            //filterContext.HttpContext.Response.StatusCode = httpException.GetHttpCode();
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            
        }
开发者ID:paulsuart,项目名称:rebelcmsxu5,代码行数:86,代码来源:HandleAuthorizationErrors.cs

示例12: LogHttpException

        private static void LogHttpException(HttpException ex, HttpContext context, RouteData routeData, BaseController controller)
        {
            int httpCode = ex.GetHttpCode();
            string message = string.Empty;
            if (httpCode == 404)
            {
                LogFileNotFound(ex, context, routeData, controller);
                return;
            }
            if ((httpCode == 400) && (routeData != null))
            {
                //if 400 came from a controller, handle it in the bad request log, not system (error) log
                LogBadRequest(ex, context, routeData, controller);
                return;
            }

            message = "Http Exception " + httpCode + " " + ex.GetHtmlErrorMessage()
                + "  \n-Message: " + ex.Message
                + "  \n-Source: " + ex.Source
                + "  \n-WebEventCode: " + ex.WebEventCode
                + "  \n-ErrorCode: " + ex.ErrorCode
                + "  \n-TargetSiteName: " + ex.TargetSite.Name
                + "  \n-StackTrace: " + ex.StackTrace;

            LogException(message, ex, Models.SystemEventLevel.Error, context, routeData, controller);
        }
开发者ID:berlstone,项目名称:GStore,代码行数:26,代码来源:ExceptionHandler.cs

示例13: HandleHttpException

        public static bool HandleHttpException(HttpException ex, bool clearError, HttpContext context, RouteData routeData, BaseController controller)
        {
            string rawUrl = context.Request.RawUrl;
            string url = context.Request.Url.ToString();
            if (Settings.AppLogSystemEventsToDb || Settings.AppLogSystemEventsToFile)
            {
                LogHttpException(ex, context, routeData, controller);
            }

            int httpCode = ex.GetHttpCode();
            if (httpCode == 404)
            {
                if (Settings.AppUseFriendlyErrorPages)
                {
                    ShowErrorPage(ErrorPage.Error_NotFound, ex.GetHttpCode(), ex, clearError, context, controller);
                    return true;
                }
                return false;
            }
            else if (httpCode == 400)
            {
                if (Settings.AppUseFriendlyErrorPages)
                {
                    ShowErrorPage(ErrorPage.Error_BadRequest, ex.GetHttpCode(), ex, clearError, context, controller);
                    return true;
                }
                return false;
            }
            else
            {
                //unhandled HTTP code
                if (Settings.AppUseFriendlyErrorPages)
                {
                    ShowErrorPage(ErrorPage.Error_HttpError, ex.GetHttpCode(), ex, clearError, context, controller);
                    return true;
                }
                return false;
            }
        }
开发者ID:berlstone,项目名称:GStore,代码行数:39,代码来源:ExceptionHandler.cs

示例14: VLogServerSideError

        /// <summary>
        ///     Initializes a new instance of the <see cref="VLogServerSideError"/> class.
        /// from a given <see cref="HttpException"/> instance and 
        /// <see cref="HttpContext"/> instance representing the HTTP 
        /// context during the exception.
        /// </summary>
        /// <param name="httpexception">The occurred server side exception</param>
        public VLogServerSideError(HttpException httpexception)
            : this()
        {
            HttpContext context = HttpContext.Current;
            if (httpexception != null && context != null)
            {
                this.ErrorMessage = httpexception.GetErrorMessage();
                this.ErrorDetails = httpexception.GetErrorErrorDetails();

                // Sets an object of a uniform resource identifier properties
                this.SetAdditionalHttpContextInfo(context);
                this.SetAdditionalExceptionInfo(httpexception);

                // If this is an HTTP exception, then get the status code
                // and detailed HTML message provided by the host.
                this.ErrorCode = httpexception.GetHttpCode();

                VLogErrorCode errorcoderule;

                if (VLog.WebErrorCodes.TryGetValue(this.ErrorCode, out errorcoderule) && !errorcoderule.ExcludeFromLogging)
                {
                    this.AddHttpExceptionData(errorcoderule, context, httpexception, errorcoderule);
                }
            }
        }
开发者ID:MGramolini,项目名称:vodca,代码行数:32,代码来源:VLogServerSideError.cs

示例15: Constructor2b_Deny_Unrestricted

		public void Constructor2b_Deny_Unrestricted ()
		{
			HttpException e = new HttpException ("message", new Exception ());
			e.GetHtmlErrorMessage (); // null for ms, non-null for mono
			Assert.AreEqual (500, e.GetHttpCode (), "HttpCode");
		}
开发者ID:nobled,项目名称:mono,代码行数:6,代码来源:HttpExceptionCas.cs


注:本文中的System.Web.HttpException.GetHttpCode方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。