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


C# Web.HttpException类代码示例

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


HttpException类属于System.Web命名空间,在下文中一共展示了HttpException类的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: LogException

        public static void LogException(HttpException exception)
        {
            if (exception != null)
            {
                Debug.Print(exception.ToString());
                Logger.Error(exception.ToString());

                try
                {
                    var error = new VLogServerSideError(exception);

                    VLogErrorCode weberrorcode = VLog.GetWebErrorCodeOrDefault(error.ErrorCode, VLogErrorTypes.ServerSideIIS);
                    if (weberrorcode != null && !weberrorcode.ExcludeFromLogging)
                    {
                        if (VLog.OnCommitExceptionToServerRepository != null)
                        {
                            VLog.OnCommitExceptionToServerRepository(error);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // IMPORTANT! We swallow any exception raised during the
                    // logging and send them out to the trace . The idea
                    // here is that logging of exceptions by itself should not
                    // be  critical to the overall operation of the application.
                    // The bad thing is that we catch ANY kind of exception,
                    // even system ones and potentially let them slip by.
                    Logger.Error(ex.ToString());
                    Debug.Print(ex.Message);
                }
            }
        }
开发者ID:MGramolini,项目名称:vodca,代码行数:33,代码来源:VLog.LogException.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: Index

 // GET: Error
 public ActionResult Index()
 {
     //If a 404 is thrown, the system redirects here but without a HandleErrorInfo object, so we make our own.
     HttpException err = new HttpException(404, string.Format("404 - Unrecognized Url - ({0})", Request.Params["aspxerrorpath"]));
     HandleErrorInfo model = new HandleErrorInfo(err, "Error", "Index");
     return View("Error", model);
 }
开发者ID:cbacon91,项目名称:VideoQuiz,代码行数:8,代码来源:ErrorController.cs

示例5: 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

示例6: Application_Error

        protected void Application_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError();

            WebServiceException webEx = exception as WebServiceException;
            if (webEx != null) {
                log.ErrorFormat("Api Error => {0}", webEx.ErrorMessage);
            }

            var httpException = new HttpException(null, exception);
            log.Error("Application Error", exception);

            if (!HttpContext.Current.IsCustomErrorEnabled)
                return;

            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Index");
            routeData.Values.Add("httpException", httpException);

            Server.ClearError();

            var errorController = ControllerBuilder.Current.GetControllerFactory().CreateController(
                new RequestContext(new HttpContextWrapper(Context), routeData), "Error");

            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
开发者ID:seba-i,项目名称:Template,代码行数:27,代码来源:Global.asax.cs

示例7: BindModel

 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
 {
     if (WebApiEnabledAttribute.IsDefined(controllerContext.Controller))
     {
         if (!controllerContext.RouteData.Values.ContainsKey(bindingContext.ModelName) && controllerContext.HttpContext.Request.HasBody())
         {
             ContentType requestFormat = controllerContext.RequestContext.GetRequestFormat();
             object model;
             if (TryBindModel(controllerContext, bindingContext, requestFormat, out model))
             {
                 bindingContext.ModelMetadata.Model = model;
                 MyDefaultModelBinder dmb = new MyDefaultModelBinder();
                 dmb.CallOnModelUpdated(controllerContext, bindingContext);
                 if (!MyDefaultModelBinder.IsModelValid(bindingContext))
                 {
                     List<ModelError> details = new List<ModelError>();
                     foreach (ModelState ms in bindingContext.ModelState.Values)
                     {
                         foreach (ModelError me in ms.Errors)
                         {
                             details.Add(me);
                         }
                     }
                     HttpException failure = new HttpException((int)HttpStatusCode.ExpectationFailed, "Invalid Model");
                     failure.Data["details"] = details;
                     throw failure;
                 }
                 return model;
             }
             throw new HttpException((int)HttpStatusCode.UnsupportedMediaType, String.Format(CultureInfo.CurrentCulture, MvcResources.Resources_UnsupportedMediaType, (requestFormat == null ? String.Empty : requestFormat.MediaType)));
         }
     }
     return this._inner.BindModel(controllerContext, bindingContext);
 }
开发者ID:huangw-t,项目名称:aspnetwebstack,代码行数:34,代码来源:ResourceModelBinder.cs

示例8: Http403

 public ActionResult Http403(HttpException exception)
 {
     return RedirectToAction(
         actionName: "SignIn",
         controllerName: "User"
         );
 }
开发者ID:Mavtak,项目名称:roomie,代码行数:7,代码来源:ErrorController.cs

示例9: Page_Load

 protected void Page_Load(object sender, EventArgs e)
 {
     // Log the exception and notify system operators
     ex = new HttpException("defaultRedirect");
     ExceptionUtility.LogException(ex, "Caught in DefaultRedirectErrorPage");
     ExceptionUtility.NotifySystemOps(ex, "Caught in DefaultRedirectErrorPage");
 }
开发者ID:jasimuddin534,项目名称:jasim_basis,代码行数:7,代码来源:DefaultRedirectErrorPage.aspx.cs

示例10: Checkout

        public ActionResult Checkout(Payment Payment)
        {
            if (new CartBusiness { UserKey = Session.GetUserKey() }.GetCurrentCartCount() <= 0)
            {
                var ex = new HttpException(400, "");
                ex.Data["ErrType"] = Globals.ERRTYPES.CART_CARTEMPTY;
                throw ex;
            }
            var orderBusiness = new OrderBusiness();
            var currentOrder = orderBusiness.GetIncompleteOrder(Session.GetUserKey());
            if (currentOrder == null)
            {
                var ex = new HttpException(404, "");
                ex.Data["ErrType"] = Globals.ERRTYPES.ORDER_NOTFOUND;
                throw ex;
            }

            decimal ItemsTotal;
            decimal ShippingPrice;
            decimal OrderTotal;
            orderBusiness.CalculateOrderSummary(out ItemsTotal, out ShippingPrice, out OrderTotal, currentOrder);
            if (OrderTotal != Payment.AmountPaid)
            {
                var ex = new HttpException(400, "");
                ex.Data["ErrType"] = Globals.ERRTYPES.CHECKOUT_PAYMENTERROR;
                throw ex;
            }

            orderBusiness.Checkout(Payment, currentOrder);

            // order completed, SEND E-MAIL

            return RedirectToAction("CheckoutComplete", currentOrder);
        }
开发者ID:linkinmal,项目名称:AntikaMarketim,代码行数:34,代码来源:OrderController.cs

示例11: 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

示例12: Application_Error

        void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            if (exception == null)
            {
                exception = new HttpException(500, "Internal Server Error", exception);
            }

            if (exception is HttpException)
            {
                HttpException httpException = exception as HttpException;
                Server.ClearError();
                Response.Clear();

                switch (httpException.GetHttpCode())
                {
                    case 404:
                        Response.Redirect("~/Error/PageNotFound");
                        break;
                    case 500:
                        Response.Redirect("~/Error/InternalServerError");
                        break;
                }
            }
        }
开发者ID:majilik,项目名称:RecruitmentSystem,代码行数:25,代码来源:Global.asax.cs

示例13: Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            // Create safe error messages.
            string generalErrorMsg = "A problem has occurred on this web site. Please try again. " +
                "If this error continues, please contact support.";
            string httpErrorMsg = "An HTTP error occurred. Page Not found. Please try again.";
            string unhandledErrorMsg = "The error was unhandled by application code.";

            // Display safe error message.
            FriendlyErrorMsg.Text = generalErrorMsg;

            // Determine where error was handled.
            string errorHandler = Request.QueryString["handler"];
            if (errorHandler == null)
            {
                errorHandler = "Error Page";
            }

            // Get the last error from the server.
            Exception ex = Server.GetLastError();

            // Get the error number passed as a querystring value.
            string errorMsg = Request.QueryString["msg"];
            if (errorMsg == "404")
            {
                ex = new HttpException(404, httpErrorMsg, ex);
                FriendlyErrorMsg.Text = ex.Message;
            }

            // If the exception no longer exists, create a generic exception.
            if (ex == null)
            {
                ex = new Exception(unhandledErrorMsg);
            }
        }
开发者ID:stojaget,项目名称:Contacts,代码行数:35,代码来源:ErrorPage.aspx.cs

示例14: Page_Load

 protected void Page_Load(object sender, EventArgs e)
 {
     // Log the exception and notify system operators
     ex = new HttpException("HTTP 404");
     ExceptionUtility.LogException(ex, "Caught in Http404ErrorPage");
     ExceptionUtility.NotifySystemOps(ex);
 }
开发者ID:hijushen,项目名称:WindowDemo,代码行数:7,代码来源:Http404ErrorPage.aspx.cs

示例15: HandleException

        public WebErrorHandler HandleException()
        {
            var exception = HttpContext.Current.Server.GetLastError();
            
            if (null != exception)
            {
                // by default 500
                var statusCode = (int)HttpStatusCode.InternalServerError;
                if (exception is HttpException)
                {
                    statusCode = new HttpException(null, exception).GetHttpCode();
                }
                else if (exception is UnauthorizedAccessException)
                {
                    // to prevent login prompt in IIS
                    // which will appear when returning 401.
                    statusCode = (int)HttpStatusCode.Forbidden;
                }

                if ((LogHttpNotFound && statusCode == 404) || statusCode != 404)
                {
                    if (null != _loggerFunc)
                    {
                        LoggerFunc(string.Format("ASP.NET Error Captured, Request URL: {0}, Exception:",
                            HttpContext.Current.Request.Url), exception);
                    }
                }

                ExceptionInfo = exception.Message;
                _statusCode = statusCode;
            }
            return this;
        }
开发者ID:EdiWang,项目名称:Edi.Web.ErrorHandler,代码行数:33,代码来源:WebErrorHandler.cs


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