public override void OnException(HttpActionExecutedContext context)
        {
            var exception = context.Exception;

            HttpException httpException;
            if (exception is DataAccessException)
            {
                httpException = MapException((DataAccessException)exception);
            }
            else if(exception is HttpException)
            {
                httpException = (HttpException)exception;
            }
            else
            {
            #if DEBUG
                return;
            #endif
                httpException = new HttpException((int)HttpStatusCode.InternalServerError, "Unexpected Error Occured.");

            }

            var statusCode = httpException.GetHttpCode();
            var response = new ApiResponse(statusCode, exception.Message);

            var content = JsonConvert.SerializeObject(response);

            context.Response = new HttpResponseMessage
            {
                StatusCode = (HttpStatusCode)statusCode,
                ReasonPhrase = exception.Message,
                Content = new StringContent(content)
            };
        }
 internal static void ThrowIfUnsupportedExtension(string virtualPath, HttpException e)
 {
     if (IsUnsupportedExtensionError(e))
     {
         var extension = Path.GetExtension(virtualPath);
         throw new HttpException(String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_FileNotSupported, extension, virtualPath));
     }
 }
        public override void OnException(HttpActionExecutedContext filterContext)
        {
            Exception exception = filterContext.Exception;

            int httpCode = new HttpException(null, exception).GetHttpCode();
            filterContext.Response = new HttpResponseMessage((HttpStatusCode)httpCode);

            Logger.Error(filterContext);
        }
        public override void Load() {
            NameValueCollection requestValueCollection = Page.RequestValueCollection;
            if (requestValueCollection == null) {
                return;
            }

            try {
                string combinedSerializedStateString = Page.RequestViewStateString;
                string persistedStateID = null;
                bool controlStateInSession = false;

                // SessionState will persist a Pair of <bool requiresControlStateInSession, string/pair>,
                // where if requiresControlStateInSession is true, second will just be the sessionID, as
                // we will store both control state and view state in session.  Otherwise, we store just the
                // view state in session and the pair will be <id, ControlState>
                if (!String.IsNullOrEmpty(combinedSerializedStateString)) {
                    Pair combinedState = (Pair)Util.DeserializeWithAssert(StateFormatter2, combinedSerializedStateString, Purpose.WebForms_SessionPageStatePersister_ClientState);
                    // Check if we are storing control state in session as well
                    if ((bool)combinedState.First) {
                        // So the second is the persistedID
                        persistedStateID = (string)combinedState.Second;
                        controlStateInSession = true;
                    }
                    else {
                        // Second is <sessionID, ControlState>
                        Pair pair = (Pair)combinedState.Second;
                        persistedStateID = (string)pair.First;
                        ControlState = pair.Second;
                    }
                }

                if (persistedStateID != null) {
                    object sessionData = Page.Session[_viewStateSessionKey + persistedStateID];
                    if (controlStateInSession) {
                        Pair combinedState = sessionData as Pair;
                        if (combinedState != null) {
                            ViewState = combinedState.First;
                            ControlState = combinedState.Second;
                        }
                    }
                    else {
                        ViewState = sessionData;
                    }
                }
            }
            catch (Exception e) {
                // Setup the formatter for this exception, to make sure this message shows up
                // in an error page as opposed to the inner-most exception's message.
                HttpException newException = new HttpException(SR.GetString(SR.Invalid_ControlState), e);
                newException.SetFormatter(new UseLastUnhandledErrorFormatter(newException));

                throw newException;
            }
        }
 internal static void ThrowIfCodeDomDefinedExtension(string virtualPath, HttpException e)
 {
     if (e is HttpCompileException)
     {
         var extension = Path.GetExtension(virtualPath);
         if (InfrastructureHelper.IsCodeDomDefinedExtension(extension))
         {
             throw new HttpException(String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_FileNotSupported, extension, virtualPath));
         }
     }
 }
Esempio n. 6
0
        /// <summary>
        /// Copy constructor that attempts to deserialize the response from the specified <seealso name="HttpException"/>.
        /// </summary>
        /// <param name="ex">Originating <see cref="PayPal.HttpException"/> object that contains the details of the exception.</param>
        public IdentityException(HttpException ex) : base(ex)
        {
            if (!string.IsNullOrEmpty(this.Response))
            {
                this.Details = JsonFormatter.ConvertFromJson<IdentityError>(this.Response);

                StringBuilder sb = new StringBuilder();
                sb.AppendLine();
                sb.AppendLine("   Error:   " + this.Details.error);
                sb.AppendLine("   Message: " + this.Details.error_description);
                sb.AppendLine("   URI:     " + this.Details.error_uri);

                this.LogMessage(sb.ToString());
            }
        }
        // Checks the exception to see if it is from CompilationUtil.GetBuildProviderTypeFromExtension, which will throw
        // an exception about an unsupported extension. 
        // Actual error format: There is no build provider registered for the extension '.txt'. You can register one in the <compilation><buildProviders> section in machine.config or web.config. Make sure is has a BuildProviderAppliesToAttribute attribute which includes the value 'Web' or 'All'. 
        internal static bool IsUnsupportedExtensionError(HttpException e)
        {
            Exception exception = e;

            // Go through the layers of exceptions to find if any of them is from GetBuildProviderTypeFromExtension
            while (exception != null)
            {
                var site = exception.TargetSite;
                if (site != null && site.Name == "GetBuildProviderTypeFromExtension" && site.DeclaringType != null && site.DeclaringType.Name == "CompilationUtil")
                {
                    return true;
                }
                exception = exception.InnerException;
            }
            return false;
        }
Esempio n. 8
0
 private void DealErroy()
 {
     HttpException erroy = new HttpException();
     string strCode = erroy.ErrorCode.ToString();
     string strMsg = erroy.Message;
     erroy.HelpLink = "sss";
     Response.Write("ErrorCode:" + strCode + "<br />");
     Response.Write("Message:" + strMsg + "<br />");
     Response.Write("HelpLink:" + erroy.HelpLink + "<br />");
     Response.Write("Source:" + erroy.Source + "<br />");
     Response.Write("TargetSite:" + erroy.TargetSite + "<br />");
     Response.Write("InnerException:" + erroy.InnerException + "<br />");
     Response.Write("StackTrace:" + erroy.StackTrace + "<br />");
     Response.Write("GetHtmlErrorMessage:" + erroy.GetHtmlErrorMessage() + "<br />");
     Response.Write("erroy.GetHttpCode().ToString():" + erroy.GetHttpCode().ToString() + "<br />");
     Response.Write("erroy.Data.ToString()::" + erroy.Data.ToString() + "<br />");
 }
Esempio n. 9
0
		void OnAuthorizeRequest (object sender, EventArgs args)
		{
			HttpApplication app = (HttpApplication) sender;
			HttpContext context = app.Context;
			if (context == null || context.SkipAuthorization)
				return;

			HttpRequest req = context.Request;
			AuthorizationSection config = (AuthorizationSection) WebConfigurationManager.GetSection ("system.web/authorization", req.Path, context);
			if (!config.IsValidUser (context.User, req.HttpMethod)) {
				HttpException e = new HttpException (401, "Unauthorized");
				HttpResponse response = context.Response;
				
				response.StatusCode = 401;
				response.Write (e.GetHtmlErrorMessage ());
				app.CompleteRequest ();
			}
		}
Esempio n. 10
0
        /// <summary>
        /// Copy constructor that attempts to deserialize the response from the specified <paramref name="PayPal.Exception.HttpException"/>.
        /// </summary>
        /// <param name="ex">Originating <see cref="PayPal.Exception.HttpException"/> object that contains the details of the exception.</param>
        public PaymentsException(HttpException ex)
            : base(ex)
        {
            if (!string.IsNullOrEmpty(this.Response))
            {
                this.Details = JsonConvert.DeserializeObject<PaymentsError>(this.Response);

                StringBuilder sb = new StringBuilder();
                sb.AppendLine();
                sb.AppendLine("   Error:    " + this.Details.name);
                sb.AppendLine("   Message:  " + this.Details.message);
                sb.AppendLine("   URI:      " + this.Details.information_link);
                sb.AppendLine("   Debug ID: " + this.Details.debug_id);

                foreach (PaymentsErrorDetails errorDetails in this.Details.details)
                {
                    sb.AppendLine("   Details:  " + errorDetails.field + " -> " + errorDetails.issue);
                }
                this.LogMessage(sb.ToString());
            }
        }
    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
        ExceptionUtility.LogException(ex, "HttpErrorPage");

        // 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 = 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();
    }
Esempio n. 12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Create safe error messages.
        string httpErrorMsg = "An HTTP error occurred. Page Not found. Please try again.";
        string unhandledErrorMsg = "The error was unhandled by application code.";

        // 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);
        }

        // Log the exception.
        ExceptionUtility.LogException(ex, errorHandler);

        // Clear the error from the server.
        Server.ClearError();
    }
Esempio n. 13
0
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
            Exception exception = actionExecutedContext.Exception;

            if (exception == null && actionExecutedContext.Response.StatusCode >= HttpStatusCode.InternalServerError)
            {
                exception = new HttpException((int)actionExecutedContext.Response.StatusCode, ResolveMessage(actionExecutedContext));
            }

            if (exception != null)
            {
                var errorMessage = exception.GetFullExceptionMessage();
                Logger.Error("UpdateAction executing: {0} {1} {2}", actionExecutedContext.Request.Method, actionExecutedContext.Request.RequestUri,errorMessage);
            }
            else
            {
                Logger.Info("UpdateAction completed: {0} {1} {2} {3}",
                            actionExecutedContext.Request.Method,
                            actionExecutedContext.Request.RequestUri,
                            actionExecutedContext.Response.StatusCode,
                            ResolveMessage(actionExecutedContext));
            }
        }
 internal static void WriteValueToStream(Object value, BinaryWriter writer) {
     if (value == null) {
         writer.Write((byte)TypeID.Null);
     } 
     else if (value is String) {
         writer.Write((byte)TypeID.String);
         writer.Write((String) value);
     }
     else if (value is Int32) {
         writer.Write((byte)TypeID.Int32);
         writer.Write((Int32) value);
     }
     else if (value is Boolean) {
         writer.Write((byte)TypeID.Boolean);
         writer.Write((Boolean) value);
     }
     else if (value is DateTime) {
         writer.Write((byte)TypeID.DateTime);
         writer.Write(((DateTime) value).Ticks);
     }
     else if (value is Decimal) {
         writer.Write((byte)TypeID.Decimal);
         int[] bits = Decimal.GetBits((Decimal)value);
         for (int i = 0; i < 4; i++) {
             writer.Write((int)bits[i]);
         }
     }
     else if (value is Byte) {
         writer.Write((byte)TypeID.Byte);
         writer.Write((byte) value);
     }
     else if (value is Char) {
         writer.Write((byte)TypeID.Char);
         writer.Write((char) value);
     }
     else if (value is Single) {
         writer.Write((byte)TypeID.Single);
         writer.Write((float) value);
     }
     else if (value is Double) {
         writer.Write((byte)TypeID.Double);
         writer.Write((double) value);
     }
     else if (value is SByte) {
         writer.Write((byte)TypeID.SByte);
         writer.Write((SByte) value);
     }
     else if (value is Int16) {
         writer.Write((byte)TypeID.Int16);
         writer.Write((short) value);
     }
     else if (value is Int64) {
         writer.Write((byte)TypeID.Int64);
         writer.Write((long) value);
     }
     else if (value is UInt16) {
         writer.Write((byte)TypeID.UInt16);
         writer.Write((UInt16) value);
     }
     else if (value is UInt32) {
         writer.Write((byte)TypeID.UInt32);
         writer.Write((UInt32) value);
     }
     else if (value is UInt64) {
         writer.Write((byte)TypeID.UInt64);
         writer.Write((UInt64) value);
     }
     else if (value is TimeSpan) {
         writer.Write((byte)TypeID.TimeSpan);
         writer.Write(((TimeSpan) value).Ticks);
     }
     else if (value is Guid) {
         writer.Write((byte)TypeID.Guid);
         Guid guid = (Guid) value;
         byte[] bits = guid.ToByteArray();
         writer.Write(bits);
     }
     else if (value is IntPtr) {
         writer.Write((byte)TypeID.IntPtr);
         IntPtr  v = (IntPtr) value;
         if (IntPtr.Size == 4) {
             writer.Write((Int32)v.ToInt32());
         }
         else {
             Debug.Assert(IntPtr.Size == 8);
             writer.Write((Int64)v.ToInt64());
         }
     }
     else if (value is UIntPtr) {
         writer.Write((byte)TypeID.UIntPtr);
         UIntPtr  v = (UIntPtr) value;
         if (UIntPtr.Size == 4) {
             writer.Write((UInt32)v.ToUInt32());
         }
         else {
             Debug.Assert(UIntPtr.Size == 8);
             writer.Write((UInt64)v.ToUInt64());
         }
     }
     else {
         writer.Write((byte)TypeID.Object);
         BinaryFormatter formatter = new BinaryFormatter();
         if (SessionStateUtility.SerializationSurrogateSelector != null) {
             formatter.SurrogateSelector = SessionStateUtility.SerializationSurrogateSelector;
         }
         try {
             formatter.Serialize(writer.BaseStream, value);
         } catch (Exception innerException) {
             HttpException outerException = new HttpException(SR.GetString(SR.Cant_serialize_session_state), innerException);
             outerException.SetFormatter(new UseLastUnhandledErrorFormatter(outerException));
             throw outerException;
         }
     }
 }
Esempio n. 15
0
 public Person GetPerson(DateTime date)
 => PeopleRepository.Database.FirstOrDefault(p => p.DoB == date)
 ?? throw HttpException.NotFound();
Esempio n. 16
0
        protected void Application_Error(object sender, EventArgs e)
        {
            HttpException lastErrorWrapper =
                Server.GetLastError() as HttpException;

            Exception lastError = lastErrorWrapper;

            if (lastErrorWrapper.InnerException != null)
            {
                lastError = lastErrorWrapper.InnerException;
            }

            string lastErrorTypeName   = lastError.GetType().ToString();
            string lastErrorMessage    = lastError.Message;
            string lastErrorStackTrace = lastError.StackTrace;

            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress("Моя компания", "*****@*****.**"));
            message.To.Add(new MailboxAddress("*****@*****.**"));
            message.Subject = "Сообщение от Микулича Егора";
            message.Body    = new BodyBuilder()
            {
                HtmlBody = string.Format(@"
            <html>
            <body>
              <h1>An Error Has Occurred!</h1>
              <table cellpadding=""5"" cellspacing=""0"" border=""1"">
              <tr>
              <tdtext-align: right;font-weight: bold"">URL:</td>
              <td>{0}</td>
              </tr>
              <tr>
              <tdtext-align: right;font-weight: bold"">User:</td>
              <td>{1}</td>
              </tr>
              <tr>
              <tdtext-align: right;font-weight: bold"">Exception Type:</td>
              <td>{2}</td>
              </tr>
              <tr>
              <tdtext-align: right;font-weight: bold"">Message:</td>
              <td>{3}</td>
              </tr>
              <tr>
              <tdtext-align: right;font-weight: bold"">Stack Trace:</td>
              <td>{4}</td>
              </tr> 
              </table>
            </body>
            </html>",
                                         Request.RawUrl,
                                         User.Identity.Name,
                                         lastErrorTypeName,
                                         lastErrorMessage,
                                         lastErrorStackTrace.Replace(Environment.NewLine, "<br />"))
            }.ToMessageBody();

            using (MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect("smtp.gmail.com", 465, true);
                client.Authenticate("*****@*****.**", "Здесь ввести пароль");
                client.Send(message);

                client.Disconnect(true);
            }
        }
Esempio n. 17
0
 /// <summary>
 /// 获取控制器的实例
 /// </summary>
 /// <param name="actionContext">上下文</param>
 /// <returns></returns>
 private IHttpController GetHttpController(ActionContext actionContext)
 {
     try
     {
         var controllerType = actionContext.Action.DeclaringService;
         var controller = this.DependencyResolver.GetService(controllerType) as HttpController;
         controller.Server = this;
         return controller;
     }
     catch (Exception ex)
     {
         var httpException = new HttpException(500, ex.Message);
         this.ProcessHttpException(httpException, actionContext);
         return null;
     }
 }
Esempio n. 18
0
        /// <summary>
        /// 处理静态资源请求
        /// </summary>
        /// <param name="extension">扩展名</param>
        /// <param name="requestContext">上下文</param>
        private void ProcessStaticFileRequest(string extension, RequestContext requestContext)
        {
            var contenType = this.MIMECollection[extension];
            var file = requestContext.Request.Url.AbsolutePath.TrimStart('/').Replace(@"/", @"\");

            if (string.IsNullOrWhiteSpace(contenType) == true)
            {
                var ex = new HttpException(403, string.Format("未配置{0}格式的MIME ..", extension));
                this.ProcessHttpException(ex, requestContext);
            }
            else if (File.Exists(file) == false)
            {
                var ex = new HttpException(404, string.Format("找不到文件{0} ..", file));
                this.ProcessHttpException(ex, requestContext);
            }
            else
            {
                var result = new FileResult { FileName = file, ContentType = contenType };
                result.ExecuteResult(requestContext);
            }
        }
Esempio n. 19
0
    private static void CheckForMultipleAspNetFormsException(HttpException ex)
    {
        MethodInfo setStringMethod = typeof(HttpContext).Assembly /* System.Web */
                .GetType("System.Web.SR")
                .GetMethod("GetString", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string) }, null);

        string multipleFormNotAllowedMessage = (string)setStringMethod.Invoke(null, new object[] { "Multiple_forms_not_allowed" });

        bool multipleAspFormTagsExists = ex.Message == multipleFormNotAllowedMessage;
        if (multipleAspFormTagsExists)
        {
            throw new HttpException("Multiple <asp:form /> elements exists on this page. ASP.NET only support one form. To fix this, insert a <asp:form> ... </asp:form> section in your template that spans all controls.");
        }
    }
Esempio n. 20
0
        /// <summary>
        /// Gets the exception.
        /// </summary>
        /// <param name="ex">The ex.</param>
        /// <param name="options">The options.</param>
        /// <returns>HttpException.</returns>
        private HttpException GetException(WebException ex, HttpRequestOptions options)
        {
            _logger.ErrorException("Error getting response from " + options.Url, ex);

            var exception = new HttpException(ex.Message, ex);

            var response = ex.Response as HttpWebResponse;
            if (response != null)
            {
                exception.StatusCode = response.StatusCode;
            }

            return exception;
        }
        /// <summary>
        /// Intercepts unhandled exceptions and crafts the error response appropriately.
        /// </summary>
        /// <param name="context">A context object.</param>
        public override void OnException(HttpActionExecutedContext context)
        {
            dynamic        errorResponsePayload = new ExpandoObject();
            HttpStatusCode errorResponseCode    = HttpStatusCode.InternalServerError;

            PartnerDomainException partnerDomainException = context.Exception as PartnerDomainException;

            if (partnerDomainException != null)
            {
                Trace.TraceError("ErrorHandler: Intercepted PartnerDomainException: {0}.", context.Exception.ToString());

                switch (partnerDomainException.ErrorCode)
                {
                case ErrorCode.SubscriptionNotFound:
                case ErrorCode.PartnerOfferNotFound:
                case ErrorCode.InvalidFileType:
                case ErrorCode.InvalidInput:
                case ErrorCode.MicrosoftOfferImmutable:
                case ErrorCode.SubscriptionExpired:
                case ErrorCode.InvalidAddress:
                case ErrorCode.DomainNotAvailable:
                case ErrorCode.MaximumRequestSizeExceeded:
                case ErrorCode.AlreadyExists:
                case ErrorCode.CardCVNCheckFailed:
                case ErrorCode.CardExpired:
                case ErrorCode.CardRefused:
                case ErrorCode.PaymentGatewayPaymentError:
                case ErrorCode.PaymentGatewayIdentityFailureDuringConfiguration:     // treat this as a retryable bad input.
                    errorResponseCode = HttpStatusCode.BadRequest;
                    break;

                case ErrorCode.PaymentGatewayFailure:
                case ErrorCode.DownstreamServiceError:
                    errorResponseCode = HttpStatusCode.BadGateway;
                    break;

                case ErrorCode.PersistenceFailure:
                case ErrorCode.SubscriptionUpdateFailure:
                case ErrorCode.ServerError:
                case ErrorCode.PaymentGatewayIdentityFailureDuringPayment:     // treat this as a non retryable server error.
                default:
                    errorResponseCode = HttpStatusCode.InternalServerError;
                    break;
                }

                errorResponsePayload.ErrorCode = partnerDomainException.ErrorCode;
                errorResponsePayload.Details   = partnerDomainException.Details;
            }
            else
            {
                errorResponsePayload.Details = new Dictionary <string, string>();
                PartnerException partnerCenterException = context.Exception as PartnerException;

                if (partnerCenterException != null &&
                    (partnerCenterException.ErrorCategory == PartnerErrorCategory.BadInput || partnerCenterException.ErrorCategory == PartnerErrorCategory.AlreadyExists))
                {
                    Trace.TraceError("ErrorHandler: Intercepted PartnerException: {0}.", context.Exception.ToString());
                    errorResponseCode = HttpStatusCode.BadRequest;

                    string errorCode = string.Empty;

                    // can be null.
                    if (partnerCenterException.ServiceErrorPayload != null)
                    {
                        switch (partnerCenterException.ServiceErrorPayload.ErrorCode)
                        {
                        case "27002":
                            errorResponsePayload.ErrorCode = ErrorCode.InvalidAddress;
                            break;

                        case "27100":
                            errorResponsePayload.ErrorCode = ErrorCode.DomainNotAvailable;
                            break;

                        default:
                            errorResponsePayload.ErrorCode = ErrorCode.InvalidInput;
                            PartnerDomainException tempException = new PartnerDomainException(ErrorCode.DownstreamServiceError).AddDetail("ErrorMessage", partnerCenterException.Message);
                            errorResponsePayload.Details = tempException.Details;
                            break;
                        }
                    }
                    else
                    {
                        // since ServiceErrorPayload is not available. Its better to mark it as downstream service error and send the exception message.
                        errorResponsePayload.ErrorCode = ErrorCode.DownstreamServiceError;
                        PartnerDomainException tempException = new PartnerDomainException(ErrorCode.DownstreamServiceError).AddDetail("ErrorMessage", partnerCenterException.Message);
                        errorResponsePayload.Details = tempException.Details;
                    }
                }
                else
                {
                    HttpException httpException = context.Exception as HttpException;

                    if (httpException != null && httpException.WebEventCode == 3004)
                    {
                        // the maximum request size has been exceeded
                        Trace.TraceError("ErrorHandler: Maximum request size exceeded: {0}.", context.Exception.ToString());

                        errorResponseCode = HttpStatusCode.BadRequest;
                        errorResponsePayload.ErrorCode = ErrorCode.MaximumRequestSizeExceeded;
                    }
                    else
                    {
                        // any other exception will be treated as a server failure or bug
                        Trace.TraceError("ErrorHandler: Intercepted Exception: {0}. Returning 500 as response.", context.Exception.ToString());

                        errorResponsePayload.ErrorCode = ErrorCode.ServerError;
                    }
                }
            }

            context.Response = new HttpResponseMessage(errorResponseCode)
            {
                Content = new StringContent(JsonConvert.SerializeObject(errorResponsePayload))
            };
        }
Esempio n. 22
0
 public Person GetPerson(string skill, int age)
 => PeopleRepository.Database.FirstOrDefault(p => string.Equals(p.MainSkill, skill, StringComparison.CurrentCultureIgnoreCase) && p.Age == age)
 ?? throw HttpException.NotFound();
Esempio n. 23
0
    private void CheckForMultipleAspNetFormsException(HttpException ex)
    {
        MethodInfo setStringMethod = typeof(HttpContext).Assembly /* System.Web */
                .GetType("System.Web.SR")
                .GetMethod("GetString", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string) }, null);

        string multipleFormNotAllowedMessage = (string)setStringMethod.Invoke(null, new object[] { "Multiple_forms_not_allowed" });

        bool multipleAspFormTagsExists = ex.Message == multipleFormNotAllowedMessage;
        if (multipleAspFormTagsExists)
        {
            string errorMessage = (this.MasterPageFile != null)
                ? "Multiple <form runat=\"server\" /> elements exist on this page." +
                  "ASP.NET supports only one visible <form runat=\"server\" /> control at a time.\n " +
                  "To fix this, insert a <form runat=\"server\"> ... </form> tag in your master page template that spans all placeholders."
                : "Multiple <asp:form /> elements exist on this page. " +
                  "ASP.NET supports only one visible <form runat=\"server\" /> control at a time.\n " +
                  "To fix this, insert a <asp:form> ... </asp:form> section in your template that spans all controls.";

            throw new HttpException(errorMessage);

        }
    }
Esempio n. 24
0
        static public void notifyException(Exception ex, Page page)
        {
            try
            {
                String texto = "";
                texto += "----------------------------------" + Environment.NewLine;
                texto += "Exception: " + ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + Environment.NewLine;

                if (ex is HttpException)
                {
                    HttpException httpEx = (HttpException)ex;
                    texto += "HttpException: " + httpEx.GetHttpCode() + Environment.NewLine + Environment.NewLine;
                }

                if (ex.InnerException != null)
                {
                    texto += "InnerException: " + ex.InnerException.Message + Environment.NewLine + ex.InnerException.StackTrace + Environment.NewLine + Environment.NewLine;

                    if (ex.InnerException.InnerException != null)
                    {
                        texto += "InnerException: " + ex.InnerException.InnerException.Message + Environment.NewLine + ex.InnerException.InnerException.StackTrace + Environment.NewLine + Environment.NewLine;
                    }
                }

                try
                {
                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "Windows User: "******"----------------------------------" + Environment.NewLine;
                    texto += "Request.Headers" + Environment.NewLine;
                    try
                    {
                        foreach (String key in page.Request.Headers.Keys)
                        {
                            texto += key + " = " + page.Request.Headers[key] + Environment.NewLine;
                        }
                    }
                    catch { }

                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "Request.Querystring" + Environment.NewLine;
                    try
                    {
                        foreach (String key in page.Request.QueryString.Keys)
                        {
                            texto += key + " = " + page.Request.QueryString[key] + Environment.NewLine;
                        }
                    }
                    catch { }

                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "Request.Form" + Environment.NewLine;
                    try
                    {
                        foreach (String key in page.Request.Form.Keys)
                        {
                            texto += key + " = " + page.Request.Form[key] + Environment.NewLine;
                        }
                    }
                    catch { }

                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "Session" + Environment.NewLine;
                    try
                    {
                        foreach (String key in page.Session.Keys)
                        {
                            texto += key + " = " + page.Session[key] + Environment.NewLine;
                        }
                    }
                    catch { }

                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "Request.Params" + Environment.NewLine;
                    try
                    {
                        foreach (String key in page.Request.Params.Keys)
                        {
                            texto += key + " = " + page.Request.Params[key] + Environment.NewLine;
                        }
                    }
                    catch { }

                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "Request.ServerVariables" + Environment.NewLine;
                    try
                    {
                        foreach (String key in page.Request.ServerVariables.Keys)
                        {
                            texto += key + " = " + page.Request.ServerVariables[key] + Environment.NewLine;
                        }
                    }
                    catch { }
                }
                texto += Environment.NewLine;

                writeExceptionText(texto);
                sendEmail("Erro em CAS", ConfigurationManager.AppSettings["to"], texto, false);
                texto = null;
            }
            catch { }
        }
Esempio n. 25
0
        /// <summary>
        /// Executing API calls
        /// </summary>
        /// <param name="payLoad"></param>
        /// <param name="httpRequest"></param>
        /// <returns>A string containing the response from the remote host.</returns>
        public string Execute(string payLoad, HttpWebRequest httpRequest)
        {
            int retriesConfigured = config.ContainsKey(BaseConstants.HttpConnectionRetryConfig) ?
                   Convert.ToInt32(config[BaseConstants.HttpConnectionRetryConfig]) : 0;
            int retries = 0;

            // Reset the request & response details
            this.RequestDetails.Reset();
            this.ResponseDetails.Reset();

            // Store the request details
            this.RequestDetails.Body = payLoad;
            this.RequestDetails.Headers = httpRequest.Headers;
            this.RequestDetails.Url = httpRequest.RequestUri.AbsoluteUri;
            this.RequestDetails.Method = httpRequest.Method;

            try
            {
                do
                {
                    if (retries > 0)
                    {
                        logger.Info("Retrying....");
                        httpRequest = CopyRequest(httpRequest, config, httpRequest.RequestUri.ToString());
                        this.RequestDetails.RetryAttempts++;
                    }
                    try
                    {
                        switch (httpRequest.Method)
                        {
                            case "POST":
                            case "PUT":
                            case "PATCH":
                                using (StreamWriter writerStream = new StreamWriter(httpRequest.GetRequestStream()))
                                {
                                    writerStream.Write(payLoad);
                                    writerStream.Flush();
                                    writerStream.Close();

                                    if (ConfigManager.IsLiveModeEnabled(config))
                                    {
                                        logger.Debug("Request details are hidden in live mode.");
                                    }
                                    else
                                    {
                                        logger.Debug(payLoad);
                                    }
                                }
                                break;

                            default:
                                break;
                        }

                        using (WebResponse responseWeb = httpRequest.GetResponse())
                        {
                            // Store the response information
                            this.ResponseDetails.Headers = responseWeb.Headers;
                            if(responseWeb is HttpWebResponse)
                            {
                                this.ResponseDetails.StatusCode = ((HttpWebResponse)responseWeb).StatusCode;
                            }

                            using (StreamReader readerStream = new StreamReader(responseWeb.GetResponseStream()))
                            {
                                this.ResponseDetails.Body = readerStream.ReadToEnd().Trim();

                                if (ConfigManager.IsLiveModeEnabled(config))
                                {
                                    logger.Debug("Response details are hidden in live mode.");
                                }
                                else
                                {
                                    logger.Debug("Service response: ");
                                    logger.Debug(this.ResponseDetails.Body);
                                }
                                return this.ResponseDetails.Body;
                            }
                        }
                    }
                    catch (WebException ex)
                    {
                        // If provided, get and log the response from the remote host.
                        var response = string.Empty;
                        if (ex.Response != null)
                        {
                            using (var readerStream = new StreamReader(ex.Response.GetResponseStream()))
                            {
                                response = readerStream.ReadToEnd().Trim();
                                logger.Error("Error response:");
                                logger.Error(response);
                            }
                        }
                        logger.Error(ex.Message);

                        ConnectionException rethrowEx = null;

                        // Protocol errors indicate the remote host received the
                        // request, but responded with an error (usually a 4xx or
                        // 5xx error).
                        if (ex.Status == WebExceptionStatus.ProtocolError)
                        {
                            var httpWebResponse = (HttpWebResponse)ex.Response;

                            // If the HTTP status code is flagged as one where we
                            // should continue retrying, then ignore the exception
                            // and continue with the retry attempt.
                            if(httpWebResponse.StatusCode == HttpStatusCode.GatewayTimeout ||
                               httpWebResponse.StatusCode == HttpStatusCode.RequestTimeout ||
                               httpWebResponse.StatusCode == HttpStatusCode.BadGateway)
                            {
                                continue;
                            }

                            rethrowEx = new HttpException(ex.Message, response, httpWebResponse.StatusCode, ex.Status, httpWebResponse.Headers, httpRequest);
                        }
                        else if(ex.Status == WebExceptionStatus.ReceiveFailure ||
                                ex.Status == WebExceptionStatus.ConnectFailure ||
                                ex.Status == WebExceptionStatus.KeepAliveFailure)
                        {
                            logger.Debug("There was a problem connecting to the server: " + ex.Status.ToString());
                            continue;
                        }
                        else if (ex.Status == WebExceptionStatus.Timeout)
                        {
                            // For connection timeout errors, include the connection timeout value that was used.
                            var message = string.Format("{0} (HTTP request timeout was set to {1}ms)", ex.Message, httpRequest.Timeout);
                            rethrowEx = new ConnectionException(message, response, ex.Status, httpRequest);
                        }
                        else
                        {
                            // Non-protocol errors indicate something happened with the underlying connection to the server.
                            rethrowEx = new ConnectionException("Invalid HTTP response: " + ex.Message, response, ex.Status, httpRequest);
                        }

                        if(ex.Response != null && ex.Response is HttpWebResponse)
                        {
                            var httpWebResponse = ex.Response as HttpWebResponse;
                            this.ResponseDetails.StatusCode = httpWebResponse.StatusCode;
                            this.ResponseDetails.Headers = httpWebResponse.Headers;
                        }

                        this.ResponseDetails.Exception = rethrowEx;
                        throw rethrowEx;
                    }
                } while (retries++ < retriesConfigured);
            }
            catch (PayPalException)
            {
                // Rethrow any PayPalExceptions since they already contain the
                // details of the exception.
                throw;
            }
            catch (System.Exception ex)
            {
                // Repackage any other exceptions to give a bit more context to
                // the caller.
                throw new PayPalException("Exception in PayPal.HttpConnection.Execute(): " + ex.Message, ex);
            }

            // If we've gotten this far, it means all attempts at sending the
            // request resulted in a failed attempt.
            throw new PayPalException("Retried " + retriesConfigured + " times.... Exception in PayPal.HttpConnection.Execute(). Check log for more details.");
        }
Esempio n. 26
0
        //HttpContext context
        static public void notifyException(Exception ex, HttpContext context)
        {
            try
            {
                String texto = "";
                texto += "----------------------------------" + Environment.NewLine;
                texto += DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + Environment.NewLine + Environment.NewLine;

                texto += "----------------------------------" + Environment.NewLine;
                texto += ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + Environment.NewLine;

                if (ex is HttpException)
                {
                    HttpException httpEx = (HttpException)ex;
                    texto += "HttpException: " + httpEx.GetHttpCode() + Environment.NewLine + Environment.NewLine;
                }

                if (ex.InnerException != null)
                {
                    texto += "InnerException: " + ex.InnerException.Message + Environment.NewLine + ex.InnerException.StackTrace + Environment.NewLine + Environment.NewLine;

                    if (ex.InnerException.InnerException != null)
                    {
                        texto += "InnerException: " + ex.InnerException.InnerException.Message + Environment.NewLine + ex.InnerException.InnerException.StackTrace + Environment.NewLine + Environment.NewLine;
                    }
                }

                try
                {
                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "HostingEnvironment Properties" + Environment.NewLine;
                    texto += "Application ID: " + HostingEnvironment.ApplicationID;
                    texto += "Application Physical Path: " + HostingEnvironment.ApplicationPhysicalPath;
                    texto += "Application Virtual Path:	" + HostingEnvironment.ApplicationVirtualPath;
                    texto += "Site Name: " + HostingEnvironment.SiteName;
                    texto += Environment.NewLine;
                }
                catch { }


                try
                {
                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "Windows User: "******"----------------------------------" + Environment.NewLine;
                    texto += "Request.Headers" + Environment.NewLine;
                    try
                    {
                        foreach (String key in context.Request.Headers.Keys)
                        {
                            texto += key + " = " + context.Request.Headers[key] + Environment.NewLine;
                        }
                    }
                    catch { }

                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "Request.Querystring" + Environment.NewLine;
                    try
                    {
                        foreach (String key in context.Request.QueryString.Keys)
                        {
                            texto += key + " = " + context.Request.QueryString[key] + Environment.NewLine;
                        }
                    }
                    catch { }

                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "Request.Form" + Environment.NewLine;
                    try
                    {
                        foreach (String key in context.Request.Form.Keys)
                        {
                            texto += key + " = " + context.Request.Form[key] + Environment.NewLine;
                        }
                    }
                    catch { }

                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "Session" + Environment.NewLine;
                    try
                    {
                        foreach (String key in context.Session.Keys)
                        {
                            texto += key + " = " + context.Session[key] + Environment.NewLine;
                        }
                    }
                    catch { }

                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "Request.Params" + Environment.NewLine;
                    try
                    {
                        foreach (String key in context.Request.Params.Keys)
                        {
                            texto += key + " = " + context.Request.Params[key] + Environment.NewLine;
                        }
                    }
                    catch { }

                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "Request.ServerVariables" + Environment.NewLine;
                    try
                    {
                        foreach (String key in context.Request.ServerVariables.Keys)
                        {
                            texto += key + " = " + context.Request.ServerVariables[key] + Environment.NewLine;
                        }
                    }
                    catch { }
                }

                texto += Environment.NewLine;

                writeExceptionText(texto);
                sendEmail("Erro em CAS", ConfigurationManager.AppSettings["to"], texto, false);
                texto = null;
            }
            catch { }
        }
        // Return true if we succeed
        private bool ParseHttpException(HttpException e)
        {
            int i;
            Match match = null;

            String errorMessage = e.GetHtmlErrorMessage();
            if (errorMessage == null)
            {
                return false;
            }

            // Use regular expressions to scrape the message output
            // for meaningful data. One problem: Some parts of the 
            // output are optional, and any regular expression that
            // uses the ()? syntax doesn't pick it up. So, we have
            // to have all the different combinations of expressions,
            // and use each one in order.

            EnsureSearchExpressions();
            for (i = 0; i < _expressionCount; i++)
            {
                match = _searchExpressions[i].Match(errorMessage);
                if (match.Success)
                {
                    break;
                }
            }

            if (i == _expressionCount)
            {
                return false;
            }

            this.Type        = TrimAndClean(match.Result("${title}"));
            this.Description = TrimAndClean(match.Result("${description}"));
            if (i <= 1)
            {
                // These expressions were able to match the miscellaneous
                // title/text section.
                this.MiscTitle = TrimAndClean(match.Result("${misctitle}"));
                this.MiscText  = TrimAndClean(match.Result("${misctext}"));
            }
            if (i == 0)
            {
                // This expression was able to match the file/line # 
                // section.
                this.File        = TrimAndClean(match.Result("${file}"));
                this.LineNumber  = TrimAndClean(match.Result("${linenumber}"));
            }

            return true;
        }
Esempio n. 28
0
        static public void notifyException(Exception ex)
        {
            try
            {
                String texto = "";
                texto += "----------------------------------" + Environment.NewLine;
                texto += DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + Environment.NewLine + Environment.NewLine;

                texto += "----------------------------------" + Environment.NewLine;
                texto += ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + Environment.NewLine;

                if (ex is HttpException)
                {
                    HttpException httpEx = (HttpException)ex;
                    texto += "HttpException: " + httpEx.GetHttpCode() + Environment.NewLine + Environment.NewLine;
                }

                if (ex.InnerException != null)
                {
                    texto += "InnerException: " + ex.InnerException.Message + Environment.NewLine + ex.InnerException.StackTrace + Environment.NewLine + Environment.NewLine;

                    if (ex.InnerException.InnerException != null)
                    {
                        texto += "InnerException: " + ex.InnerException.InnerException.Message + Environment.NewLine + ex.InnerException.InnerException.StackTrace + Environment.NewLine + Environment.NewLine;
                    }
                }


                try
                {
                    texto += Environment.NewLine;
                    texto += "----------------------------------" + Environment.NewLine;
                    texto += "HostingEnvironment Properties" + Environment.NewLine;
                    texto += "Application ID: " + HostingEnvironment.ApplicationID;
                    texto += "Application Physical Path: " + HostingEnvironment.ApplicationPhysicalPath;
                    texto += "Application Virtual Path:	" + HostingEnvironment.ApplicationVirtualPath;
                    texto += "Site Name: " + HostingEnvironment.SiteName;
                    texto += Environment.NewLine;
                }
                catch { }

                texto += Environment.NewLine;
                texto += "----------------------------------" + Environment.NewLine;
                try
                {
                    texto += "Windows User: "******"plugins"));

                    //texto += "Physical Directory: " + WindowsIdentity.GetCurrent().Name + Environment.NewLine;
                }
                catch { }

                try
                {
                    texto += "Environment Directory: " + Environment.CurrentDirectory + Environment.NewLine;
                }
                catch { }


                texto += Environment.NewLine;


                writeExceptionText(texto);
                sendEmail("Erro em CAS", ConfigurationManager.AppSettings["to"], texto, false);
                texto = null;
            }
            catch { }
        }
Esempio n. 29
0
 /// <summary>
 /// 处理一般的请求
 /// </summary>
 /// <param name="route">路由</param>
 /// <param name="context">上下文</param>
 /// <param name="requestContext">请求上下文</param>
 private void ProcessActionRequest(string route, IContenxt context, RequestContext requestContext)
 {
     var action = this.httpActionList.TryGet(requestContext.Request);
     if (action == null)
     {
         var ex = new HttpException(404, "找不到路径" + route);
         this.ProcessHttpException(ex, requestContext);
     }
     else
     {
         this.ExecuteHttpAction(action, context, requestContext);
     }
 }
        private static void CreateMdfFile(string fullFileName, string dataDir, string connectionString) {
            bool creatingDir = false;
            string databaseName = null;
            HttpContext context = HttpContext.Current;
            string tempFileName = null;

            try {
                if (!Directory.Exists(dataDir)) {
                    creatingDir = true;
                    Directory.CreateDirectory(dataDir);
                    creatingDir = false;
                    try {
                        if (context != null)
                            HttpRuntime.RestrictIISFolders(context);
                    }
                    catch { }
                }

                fullFileName = fullFileName.ToUpper(CultureInfo.InvariantCulture);
                char[] strippedFileNameChars = Path.GetFileNameWithoutExtension(fullFileName).ToCharArray();
                for (int iter = 0; iter < strippedFileNameChars.Length; iter++)
                    if (!char.IsLetterOrDigit(strippedFileNameChars[iter]))
                        strippedFileNameChars[iter] = '_';
                string strippedFileName = new string(strippedFileNameChars);
                if (strippedFileName.Length > 30)
                    databaseName = strippedFileName.Substring(0, 30) + "_" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
                else
                    databaseName = strippedFileName + "_" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);

                tempFileName = Path.Combine(Path.GetDirectoryName(fullFileName), strippedFileName + "_TMP" + s_strSqlExprFileExt);

                // Auto create the temporary database
                SqlServices.Install(databaseName, tempFileName, connectionString);
                DetachDB(databaseName, connectionString);
                try {
                    File.Move(tempFileName, fullFileName);
                }
                catch {
                    if (!File.Exists(fullFileName)) {
                        File.Copy(tempFileName, fullFileName);
                        try {
                            File.Delete(tempFileName);
                        }
                        catch { }
                    }
                }
                try {
                    File.Delete(tempFileName.Replace("_TMP.MDF", "_TMP_log.LDF"));
                }
                catch { }
            }
            catch (Exception e) {
                if (context == null || context.IsCustomErrorEnabled)
                    throw;
                HttpException httpExec = new HttpException(e.Message, e);
                if (e is UnauthorizedAccessException)
                    httpExec.SetFormatter(new SqlExpressConnectionErrorFormatter(creatingDir ? DataConnectionErrorEnum.CanNotCreateDataDir : DataConnectionErrorEnum.CanNotWriteToDataDir));
                else
                    httpExec.SetFormatter(new SqlExpressDBFileAutoCreationErrorFormatter(e));
                throw httpExec;
            }
        }
Esempio n. 31
0
 /// <summary>
 /// 处理Http异常
 /// </summary>
 /// <param name="ex">Http异常</param>
 /// <param name="context">请求上下文</param>
 private void ProcessHttpException(HttpException ex, RequestContext context)
 {
     var exceptionContent = new ExceptionContext(context, ex);
     this.ExecGlobalExceptionFilters(exceptionContent);
     var result = exceptionContent.Result ?? new ErrorResult(ex);
     result.ExecuteResult(context);
 }
Esempio n. 32
0
        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);
            }

            // Show error details to only you (developer). LOCAL ACCESS ONLY
            if (Request.IsLocal)
            {
                // Detailed Error Message.
                ErrorDetailedMsg.Text = ex.Message;

                // Show where the error was handled.
                ErrorHandler.Text = errorHandler;

                // Show local access details.
                DetailedErrorPanel.Visible = true;

                if (ex.InnerException != null)
                {
                    InnerMessage.Text = ex.GetType().ToString() + "<br/>" + ex.InnerException.Message;
                    InnerTrace.Text   = ex.InnerException.StackTrace;
                }
                else
                {
                    InnerMessage.Text = ex.GetType().ToString();
                    if (ex.StackTrace != null)
                    {
                        InnerTrace.Text = ex.StackTrace.ToString().TrimStart();
                    }
                }
            }

            // Log the exception
            ExceptionUtility.LogException(ex, errorHandler);

            // Clear the error from the server.
            Server.ClearError();
        }
Esempio n. 33
0
 /// <summary>
 /// 异常时
 /// </summary>
 /// <param name="session">产生异常的会话</param>
 /// <param name="exception">异常</param>
 protected virtual void OnException(ISession session, Exception exception)
 {
     var httpException = exception as HttpException;
     if (httpException == null)
     {
         httpException = new HttpException(500, exception.Message);
     }
     var result = new ErrorResult(httpException);
     var response = new HttpResponse(session);
     result.ExecuteResult(response);
 }
Esempio n. 34
0
        /// <summary>
        /// Transforms the specified exception as appropriate into a fault message that can be sent
        /// back to the client.
        /// </summary>
        /// <remarks>
        /// This method will also trace the exception if tracing is enabled.
        /// </remarks>
        /// <param name="e">The exception that was caught.</param>
        /// <param name="hideStackTrace">same as <see cref="HttpContext.IsCustomErrorEnabled"/> <c>true</c> means dont send stack traces</param>
        /// <returns>The exception to return.</returns>
        internal static FaultException <DomainServiceFault> CreateFaultException(Exception e, bool hideStackTrace)
        {
            Debug.Assert(!e.IsFatal(), "Fatal exception passed in");
            DomainServiceFault fault = new DomainServiceFault();

            // Unwrap any TargetInvocationExceptions to get the real exception.
            e = ExceptionHandlingUtility.GetUnwrappedException(e);

            // we always send back a 200 (i.e. not re-throwing) with the actual error code in
            // the results (except fo 404) because silverlight only supports 404/500 error code. If customErrors
            // are disabled, we'll also send the error message.
            int errorCode = (int)HttpStatusCode.InternalServerError;

            if (e is InvalidOperationException)
            {
                // invalid operation exception at root level generates BadRequest
                errorCode = (int)HttpStatusCode.BadRequest;
            }
            else if (e is UnauthorizedAccessException)
            {
                errorCode = (int)HttpStatusCode.Unauthorized;
            }
            else
            {
                DomainException dpe = e as DomainException;
                if (dpe != null)
                {
                    // we always propagate error info to the client for DomainServiceExceptions
                    fault.ErrorCode         = dpe.ErrorCode;
                    fault.ErrorMessage      = FormatExceptionMessage(dpe);
                    fault.IsDomainException = true;
                    if (!hideStackTrace)
                    {
                        // also send the stack trace if custom errors is disabled
                        fault.StackTrace = dpe.StackTrace;
                    }

                    return(new FaultException <DomainServiceFault>(fault, new FaultReason(new FaultReasonText(fault.ErrorMessage ?? String.Empty, CultureInfo.CurrentCulture))));
                }
                else
                {
                    HttpException httpException = e as HttpException;
                    if (httpException != null)
                    {
                        errorCode = httpException.GetHttpCode();
                        if (errorCode == (int)HttpStatusCode.NotFound)
                        {
                            // for NotFound errors, we don't provide detailed error
                            // info, we just rethrow
                            throw e;
                        }
                    }
                }
            }

            // set error code. Also set error message if custom errors is disabled
            fault.ErrorCode = errorCode;
            if (!hideStackTrace)
            {
                fault.ErrorMessage = FormatExceptionMessage(e);
                fault.StackTrace   = e.StackTrace;
            }

            return(new FaultException <DomainServiceFault>(fault, new FaultReason(new FaultReasonText(fault.ErrorMessage ?? String.Empty, CultureInfo.CurrentCulture))));
        }
Esempio n. 35
0
        private void StreamFile(HttpContext context)
        {
            try
            {
                var fileId = context.Request.Query[FilesLinkUtility.FileId];
                var auth   = context.Request.Query[FilesLinkUtility.AuthKey];
                var userId = context.Request.Query[CommonLinkUtility.ParamName_UserUserID];

                Logger.Debug("GoogleDriveApp: get file stream " + fileId);

                var validateResult = EmailValidationKeyProvider.ValidateEmailKey(fileId + userId, auth, Global.StreamUrlExpire);
                if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok)
                {
                    var exc = new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException);

                    Logger.Error(string.Format("GoogleDriveApp: validate error {0} {1}: {2}", FilesLinkUtility.AuthKey, validateResult, context.Request.Url()), exc);

                    throw exc;
                }

                Token token = null;

                if (Guid.TryParse(userId, out var userIdGuid))
                {
                    token = TokenHelper.GetToken(AppAttr, userIdGuid);
                }

                if (token == null)
                {
                    Logger.Error("BoxApp: token is null");
                    throw new SecurityException("Access token is null");
                }

                var driveFile = GetDriveFile(fileId, token);

                var jsonFile = JObject.Parse(driveFile);

                var downloadUrl = GoogleLoginProvider.GoogleUrlFile + fileId + "?alt=media";

                if (string.IsNullOrEmpty(downloadUrl))
                {
                    Logger.Error("GoogleDriveApp: downloadUrl is null");
                    throw new Exception("downloadUrl is null");
                }

                Logger.Debug("GoogleDriveApp: get file stream downloadUrl - " + downloadUrl);

                var request = (HttpWebRequest)WebRequest.Create(downloadUrl);
                request.Method = "GET";
                request.Headers.Add("Authorization", "Bearer " + token);

                using (var response = request.GetResponse())
                    using (var stream = new ResponseStream(response))
                    {
                        stream.StreamCopyTo(context.Response.Body);

                        var contentLength = jsonFile.Value <string>("size");
                        Logger.Debug("GoogleDriveApp: get file stream contentLength - " + contentLength);
                        context.Response.Headers.Add("Content-Length", contentLength);
                    }
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Response.WriteAsync(ex.Message).Wait();
                Logger.Error("GoogleDriveApp: Error request " + context.Request.Url(), ex);
            }
            try
            {
                context.Response.Body.Flush();
                //TODO
                //context.Response.SuppressContent = true;
                //context.ApplicationInstance.CompleteRequest();
            }
            catch (HttpException ex)
            {
                Logger.Error("GoogleDriveApp StreamFile", ex);
            }
        }
 /// <summary>
 /// Invokes the <see cref="IErrorFormatter.Format"/> and guards against any exceptions that it might throw.
 /// </summary>
 /// <param name="response">Response to send back</param>
 /// <param name="msg">Request pipeline message</param>
 /// <param name="exception">Caught exception</param>
 protected virtual void FormatException(IResponse response, ReceivedHttpRequest msg, HttpException exception)
 {
     var formatterContext = new ErrorFormatterContext(exception, msg.HttpRequest, response);
     try
     {
         _formatter.Format(formatterContext);
     }
     catch (Exception err)
     {
         _logger.Error(
             string.Format("Formatter '{0}' failed to process request.", _formatter.GetType().FullName), err);
         var formatter = new SimpleErrorFormatter();
         formatter.Format(formatterContext);
     }
 }
Esempio n. 37
0
                // Wraps HttpException as inner exception in CommunicationException or ProtocolException (which derives from CommunicationException)
                static Exception CreateCommunicationException(HttpException hostedException)
                {
                    if (hostedException.WebEventCode == WebEventCodes.RuntimeErrorPostTooLarge)
                    {
                        // This HttpException is thrown if greater than httpRuntime/maxRequestLength bytes have been read from the stream.
                        // Note that this code path can only be hit when GetBufferedInputStream() is called in HostedHttpRequestAsyncResult.GetInputStream(), which only
                        // happens when an Http Module which is executed before the WCF Http Handler has accessed the request stream via GetBufferedInputStream().
                        // This is the only case that throws because GetBufferlessInputStream(true) ignores maxRequestLength, and InputStream property throws when invoked, not when stream is read.
                        return HttpInput.CreateHttpProtocolException(SR.Hosting_MaxRequestLengthExceeded, HttpStatusCode.RequestEntityTooLarge, null, hostedException);
                    }
                    else
                    {
                        // This HttpException is thrown if client disconnects and a read operation is invoked on the stream.
                        return new CommunicationException(hostedException.Message, hostedException);
                    }

                }
Esempio n. 38
0
		/// <summary>
		/// Generate a HTTP error page (that will be added to the response body).
		/// response status code is also set.
		/// </summary>
		/// <param name="response">Response that the page will be generated in.</param>
		/// <param name="err">exception.</param>
		protected virtual void ErrorPage(IHttpResponse response, HttpException err)
		{
			response.Reason = err.GetType().Name;
			response.Status = err.HttpStatusCode;
			response.ContentType = "text/plain";
			StreamWriter writer = new StreamWriter(response.Body);
#if DEBUG
            writer.WriteLine(err);
#else
			writer.WriteLine(err.Message);
#endif
			writer.Flush();
		}
Esempio n. 39
-1
 /// <summary>
 /// Http错误结果
 /// </summary>
 /// <param name="ex">http异常</param>
 /// <exception cref="ArgumentNullException"></exception>
 public ErrorResult(HttpException ex)
 {
     if (ex == null)
     {
         throw new ArgumentNullException();
     }
     this.Status = ex.Status;
     this.Errors = ex.Message;
 }