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));
         }
     }
 }
        /// <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;
        }
Example #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 />");
 }
		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 ();
			}
		}
        /// <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();
    }
Example #12
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));
            }
        }
Example #13
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();
    }
Example #14
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);
 }
Example #15
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;
     }
 }
Example #16
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);
     }
 }
Example #17
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);
            }
        }
        // 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;
        }
Example #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.");
        }
    }
        /// <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;
        }
Example #21
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);

        }
    }
 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;
         }
     }
 }
 /// <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);
 }
        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;
            }
        }
Example #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.");
        }
 /// <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);
     }
 }
Example #27
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);
                    }

                }
Example #28
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();
		}
Example #29
-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;
 }