• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Net.WebException类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



WebException类属于System.Net命名空间,在下文中一共展示了WebException类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ThrowSharpBoxExceptionBasedOnNetworkErrorCode

 internal static void ThrowSharpBoxExceptionBasedOnNetworkErrorCode(WebRequest uploadRequest, int code, WebException e)
 {
     if (Convert.ToInt32(code) == 507)
         throw new SharpBoxException(SharpBoxErrorCodes.ErrorInsufficientDiskSpace, e, uploadRequest, null);
     else
         throw new SharpBoxException(SharpBoxErrorCodes.ErrorCreateOperationFailed, e, uploadRequest, null);
 }
开发者ID:ridhouan,项目名称:teamlab.v6.5,代码行数:7,代码来源:SharpBoxException.cs


示例2: MediaRetryPolicyTestExecuteActionNonTransient

        public void MediaRetryPolicyTestExecuteActionNonTransient()
        {
            MediaRetryPolicy target = new TestMediaServicesClassFactory(null).GetSaveChangesRetryPolicy();

            int exceptionCount = 2;
            int expected = 10;
            var fakeException = new WebException("test", WebExceptionStatus.RequestCanceled);

            Func<int> func = () =>
            {
                if (--exceptionCount > 0) throw fakeException;
                return expected;
            };

            try
            {
                target.ExecuteAction(func);
            }
            catch (WebException x)
            {
                Assert.AreEqual(1, exceptionCount);
                Assert.AreEqual(fakeException, x);
                throw;
            }

            Assert.Fail("Expected exception");
        }
开发者ID:quintinb,项目名称:azure-sdk-for-media-services,代码行数:27,代码来源:MediaRetryPolicyTest.cs


示例3: SerializeWebException

        public static string SerializeWebException(WebException ex)
        {
            var dictionary = new Dictionary<string, string>();
            dictionary["StatusCode"] = ((int)((HttpWebResponse)(ex.Response)).StatusCode).ToString();
            Stream responseStream = ex.Response.GetResponseStream();
            if (responseStream != null)
            {
                dictionary["Body"] = StreamToString(responseStream);
                responseStream.Position = 0;

                if (ex.Response.Headers.AllKeys.Contains("WWW-Authenticate", StringComparer.OrdinalIgnoreCase))
                {
                    dictionary["WWW-AuthenticateHeader"] = ex.Response.Headers["WWW-Authenticate"];
                }
            }
            else
            {
                dictionary["Body"] = string.Empty;
            }

            using (Stream stream = new MemoryStream())
            {
                SerializeDictionary(dictionary, stream);
                stream.Seek(0, SeekOrigin.Begin);
                return EncodingHelper.Base64Encode(StreamToString(stream));
            }
        }
开发者ID:ankurchoubeymsft,项目名称:azure-activedirectory-library-for-dotnet,代码行数:27,代码来源:SerializationHelper.cs


示例4: HandleDownloadException

        private static void HandleDownloadException(string url, WebException ex, Failed failed)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("Failed to download '{0}'.", url);
            builder.Append("\r\n");

            // do we have a response...
            if (ex.Response != null)
            {
                try
                {
                    Stream stream = ex.Response.GetResponseStream();
                    if (stream == null)
                        throw new InvalidOperationException("'stream' is null.");
                    using (stream)
                    {
                        builder.Append("Response data: ");

                        // reader...
                        using (StreamReader reader = new StreamReader(stream))
                            builder.Append(reader.ReadToEnd());
                    }
                }
                catch (Exception readEx)
                {
                    builder.AppendFormat("An exception occurred when reading error data: " + readEx.Message);
                }
            }
            else
                builder.Append("(No response)");

            // defer to the context...
            failed(new InvalidOperationException(builder.ToString(), ex));
        }
开发者ID:mbrit,项目名称:AmxMobile.Phone7.SixBookmarks-1.2,代码行数:34,代码来源:HttpHelper.cs


示例5: GetOperationTest

        public void GetOperationTest()
        {
            var data = new OperationData { Id = "1", State = OperationState.Succeeded.ToString() };

            var dataContextMock = new Mock<IMediaDataServiceContext>();

            var fakeException = new WebException("test", WebExceptionStatus.ConnectionClosed);

            var fakeResponse = new OperationData[] { data };
            int exceptionCount = 2;

            dataContextMock.Setup((ctxt) => ctxt
                .Execute<OperationData>(It.IsAny<Uri>()))
                .Returns(() =>
                {
                    if (--exceptionCount > 0) throw fakeException;
                    return fakeResponse;
                });

            _mediaContext.MediaServicesClassFactory = new TestMediaServicesClassFactory(dataContextMock.Object);
            var actual = _mediaContext.Operations.GetOperation(data.Id);
            Assert.AreEqual(data.Id, actual.Id);

            dataContextMock.Verify((ctxt) => ctxt.Execute<OperationData>(It.IsAny<Uri>()), Times.Exactly(2));
        }
开发者ID:Ginichen,项目名称:azure-sdk-for-media-services,代码行数:25,代码来源:OperationTests.cs


示例6: Next

        public IAuthenticator Next(WebException ex)
        {
            // No user name provided, just throw
            if (string.IsNullOrEmpty(_user))
                return null;

            var response = (HttpWebResponse)ex.Response;
            var header = response.Headers["WWW-Authenticate"];

            if (response.StatusCode != HttpStatusCode.Unauthorized ||
                string.IsNullOrEmpty(header))
                return null;

            if (header.StartsWith("Digest ",
                StringComparison.InvariantCultureIgnoreCase))
            {
                var digest = new DigestToken(header,
                    _user, _password);

                return new DigestAuthenticator(digest);
            }

            // Probably bad username/password
            return null;
        }
开发者ID:oldlaurel,项目名称:WinPass,代码行数:25,代码来源:BasicAuthenticator.cs


示例7: GetWebException

 private WebException GetWebException(Stream responseStream )
 {
     var webResponse = Substitute.For<HttpWebResponse>();
     webResponse.GetResponseStream().Returns(responseStream);
     var wex = new WebException("test", null, WebExceptionStatus.UnknownError, webResponse);
     return wex; 
 }
开发者ID:warpzone81,项目名称:AccountRight_Live_API_.Net_SDK,代码行数:7,代码来源:ExceptionExtensionsTests.cs


示例8: SDataException

        /// <summary>
        /// Initializes a new instance.
        /// </summary>
        /// <param name="innerException"></param>
        public SDataException(WebException innerException)
            : base(innerException.Message, innerException, innerException.Status, innerException.Response)
        {
            if (Response == null)
            {
                return;
            }

            var httpResponse = Response as HttpWebResponse;
            _statusCode = httpResponse != null ? httpResponse.StatusCode : (HttpStatusCode?) null;
            MediaType mediaType;

            if (MediaTypeNames.TryGetMediaType(Response.ContentType, out mediaType) && mediaType == MediaType.Xml)
            {
                var serializer = new XmlSerializer(typeof (Diagnosis));

                using (var stream = Response.GetResponseStream())
                {
                    try
                    {
                        _diagnosis = (Diagnosis) serializer.Deserialize(stream);
                    }
                    catch (XmlException)
                    {
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }
            }
        }
开发者ID:GeneArnold,项目名称:SDataCSharpClientLib,代码行数:35,代码来源:SDataException.cs


示例9: HandleWebException

        private static FeedVerificationResult HandleWebException(WebException exception, string source)
        {
            try
            {
                var httpWebResponse = (HttpWebResponse)exception.Response;
                if (ReferenceEquals(httpWebResponse, null))
                {
                    return FeedVerificationResult.Invalid;
                }

                if ((int)httpWebResponse.StatusCode == 403)
                {
                    return FeedVerificationResult.Valid;
                }

                if (exception.Status == WebExceptionStatus.ProtocolError)
                {
                    return httpWebResponse.StatusCode == HttpStatusCode.Unauthorized
                        ? FeedVerificationResult.AuthenticationRequired
                        : FeedVerificationResult.Invalid;
                }                
            }
            catch (Exception ex)
            {
                Log.Debug(ex, "Failed to verify feed '{0}'", source);
            }

            return FeedVerificationResult.Invalid;
        }
开发者ID:WildGums,项目名称:Orc.NuGetExplorer,代码行数:29,代码来源:NuGetFeedVerificationService.cs


示例10: extractErrorDetails

 private string extractErrorDetails(WebException ex)
 {
     string responseBody = "";
     using (WebResponse response = ex.Response)
     {
         HttpWebResponse httpResponse = (HttpWebResponse)response;
         if (httpResponse != null)
         {
             responseStatusCode = httpResponse.StatusCode;
             if (httpResponse.StatusCode == HttpStatusCode.BadRequest)
             {
                 using (Stream data = response.GetResponseStream())
                 using (var reader = new StreamReader(data))
                 {
                     responseBody = reader.ReadToEnd();
                 }
             }
         }
         if (responseBody == "")
         {
             responseBody = "{\"Exception\":\"" + ex.Message + "\"}";
         }
     }
     return responseBody;
 }
开发者ID:ministryofjustice,项目名称:adp_api_client,代码行数:25,代码来源:HttpClient.cs


示例11: IsNetworkUnavailableFrom

		public static bool IsNetworkUnavailableFrom(WebException e)
		{
			return IsNetworkApproximatelyUnavailable () ||
				e.Status == WebExceptionStatus.NameResolutionFailure ||
				e.Status == WebExceptionStatus.Timeout ||
				e.Status == WebExceptionStatus.ConnectFailure;
		}
开发者ID:AnotherGameCompany,项目名称:FC-BlazeIt,代码行数:7,代码来源:Utils.cs


示例12: TestSendDeleteOperationRetry

        public void TestSendDeleteOperationRetry()
        {
            var data = new StreamingEndpointData { Name = "testData", Id = "1" };

            var fakeException = new WebException("test", WebExceptionStatus.ConnectionClosed);

            var dataContextMock = TestMediaServicesClassFactory.CreateSaveChangesMock(fakeException, 2, data);

            dataContextMock.Setup((ctxt) => ctxt.AttachTo("StreamingEndpoints", data));
            dataContextMock.Setup((ctxt) => ctxt.DeleteObject(data));

            _mediaContext.MediaServicesClassFactory = new TestMediaServicesClassFactory(dataContextMock.Object);

            data.SetMediaContext(_mediaContext);

            try
            {
                data.SendDeleteOperation();
            }
            catch (NotImplementedException x)
            {
                Assert.AreEqual(TestMediaDataServiceResponse.TestMediaDataServiceResponseExceptionMessage, x.Message);
            }

            dataContextMock.Verify((ctxt) => ctxt.SaveChanges(), Times.Exactly(2));
        }
开发者ID:Ginichen,项目名称:azure-sdk-for-media-services,代码行数:26,代码来源:StreamingEndpointTests.cs


示例13: UploadData

        public void UploadData(byte[] data)
        {
            try
            {
                //this.m_Method = method;//this sets someone else
                request.ContentLength = data.Length;//this is my responsability to set

                this.UploadBits( request.GetRequestStream(), null,data, null, null);
                
                //buffer2 = this.DownloadBits(request, null, null, null);
            }
            catch (Exception exception)
            {
                if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException))
                {
                    throw;
                }
                if (!(exception is WebException) && !(exception is SecurityException))
                {
                    exception = new WebException("Curl", exception);
                }
                AbortRequest();
                throw exception;
            }
        }
开发者ID:Ashod,项目名称:Phalanger,代码行数:25,代码来源:HttpBitsUploader.cs


示例14: AppendHttpResponseDetails

        private void AppendHttpResponseDetails(StringBuilder stringBuilder, WebException exception)
        {
            var httpWebResponse = exception.Response as HttpWebResponse;
              if (httpWebResponse == null)
            return;

              try
              {
            stringBuilder.AppendFormat ("StatusCode: {0}", httpWebResponse.StatusCode);
            stringBuilder.AppendLine();

            stringBuilder.AppendFormat ("StatusDescription: {0}", httpWebResponse.StatusDescription);
            stringBuilder.AppendLine();

            try
            {
              using (var reader = new StreamReader (httpWebResponse.GetResponseStream()))
              {
            stringBuilder.AppendFormat ("Body: {0}", reader.ReadToEnd());
            stringBuilder.AppendLine();
              }
            }
            catch (ProtocolViolationException)
            {
              // Occurs if there is no response stream and can be ignored
            }
              }
              catch (Exception x)
              {
            s_logger.Error ("Exception while getting exception details.", x);
              }
        }
开发者ID:nertsch,项目名称:outlookcaldavsynchronizer,代码行数:32,代码来源:ExceptionHandler.cs


示例15: ContentKeyBaseCollectionGetProtectionKeyIdForContentKeyRetry

        public void ContentKeyBaseCollectionGetProtectionKeyIdForContentKeyRetry()
        {
            var dataContextMock = new Mock<IMediaDataServiceContext>();

            var fakeException = new WebException("test", WebExceptionStatus.ConnectionClosed);

            var fakeResponse = new string[] { "testKey" };
            int exceptionCount = 2;

            dataContextMock.Setup((ctxt) => ctxt
                .Execute<string>(It.IsAny<Uri>()))
                .Returns(() =>
                {
                    if (--exceptionCount > 0) throw fakeException;
                    return fakeResponse;
                });

            _mediaContext.MediaServicesClassFactory = new TestMediaServicesClassFactory(dataContextMock.Object);

            var actual = ContentKeyBaseCollection.GetProtectionKeyIdForContentKey(_mediaContext, ContentKeyType.CommonEncryption);

            Assert.AreEqual(fakeResponse[0], actual);

            dataContextMock.Verify((ctxt) => ctxt.Execute<string>(It.IsAny<Uri>()), Times.Exactly(2));
        }
开发者ID:votrongdao,项目名称:azure-sdk-for-media-services,代码行数:25,代码来源:ContentKeyTest.cs


示例16: HandleConnection

        private static void HandleConnection(WebException ex)
        {
            Log.Error(ex);
            StatusNotification.Notify("Connection failed");

            if (ex.Status == WebExceptionStatus.NameResolutionFailure)
            {
                MessageBox.Show("Could not find the server. Please check the URL.", "Connection failed", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else if ( ex.Response is HttpWebResponse)
            {
                var response = (HttpWebResponse)ex.Response;

                switch (response.StatusCode)
                {
                    case HttpStatusCode.BadGateway:
                        MessageBox.Show("Could not find the server. Please check the URL.", "Connection failed", MessageBoxButton.OK, MessageBoxImage.Information);
                        break;
                    case HttpStatusCode.Unauthorized:
                    case HttpStatusCode.Forbidden:
                        MessageBox.Show("You are not authorized to open this site", "Connection failed", MessageBoxButton.OK, MessageBoxImage.Information);
                        break;
                    default:
                        MessageBox.Show(ex.Message, "Connection failed", MessageBoxButton.OK, MessageBoxImage.Information);
                        break;
                }
            }
            else
                MessageBox.Show(ex.ToString(), "Connection failed", MessageBoxButton.OK, MessageBoxImage.Information);
        }
开发者ID:konradsikorski,项目名称:smartCAML,代码行数:30,代码来源:ExceptionHandler.cs


示例17: TestNotificationEndPointCreateFailedRetryMessageLengthLimitExceeded

        public void TestNotificationEndPointCreateFailedRetryMessageLengthLimitExceeded()
        {
            var expected = new NotificationEndPoint { Name = "testData" };

            var fakeException = new WebException("test", WebExceptionStatus.MessageLengthLimitExceeded);

            var dataContextMock = TestMediaServicesClassFactory.CreateSaveChangesMock(fakeException, 10, expected);

            dataContextMock.Setup((ctxt) => ctxt.AddObject("NotificationEndPoints", It.IsAny<object>()));

            _mediaContext.MediaServicesClassFactory = new TestMediaServicesClassFactory(dataContextMock.Object);

            try
            {
                _mediaContext.NotificationEndPoints.Create("Empty", NotificationEndPointType.AzureQueue, "127.0.0.1");
            }
            catch (WebException x)
            {
                dataContextMock.Verify((ctxt) => ctxt.SaveChangesAsync(It.IsAny<object>()), Times.Exactly(1));
                Assert.AreEqual(fakeException, x);
                throw;
            }

            Assert.Fail("Expected exception");
        }
开发者ID:votrongdao,项目名称:azure-sdk-for-media-services,代码行数:25,代码来源:NotificationEndPointTests.cs


示例18: GetSummaryFromWebException

        public static TaskCompletedSummary GetSummaryFromWebException(string taskName, WebException e)
        {
            var webResponse = e.Response as HttpWebResponse;
            if (webResponse != null && webResponse.StatusCode == HttpStatusCode.Unauthorized)
            {
                //// "Access denied // check credentials"
                return new TaskCompletedSummary { Task = taskName, Result = TaskSummaryResult.AccessDenied };
            }

            string response;
            using (var stream = e.Response.GetResponseStream())
            {
                var buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                response = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);
            }

            if (string.IsNullOrEmpty(response))
            {
                //// "Can not connect to server // check conectivity";
                return new TaskCompletedSummary { Task = taskName, Result = TaskSummaryResult.UnreachableServer };
            }

            return new TaskCompletedSummary { Task = taskName, Result = TaskSummaryResult.UnknownError };
        }
开发者ID:piredman,项目名称:MobileMilk,代码行数:25,代码来源:ExceptionHandling.cs


示例19: DisplayWebException

 void DisplayWebException( WebException ex, string action )
 {
     ErrorHandler.LogError( action, ex );
     if( ex.Status == WebExceptionStatus.Timeout ) {
         string text = "&eFailed to " + action + ":" +
             Environment.NewLine + "Timed out while connecting to classicube.net.";
         SetStatus( text );
     } else if( ex.Status == WebExceptionStatus.ProtocolError ) {
         HttpWebResponse response = (HttpWebResponse)ex.Response;
         int errorCode = (int)response.StatusCode;
         string description = response.StatusDescription;
         string text = "&eFailed to " + action + ":" +
             Environment.NewLine + " classicube.net returned: (" + errorCode + ") " + description;
         SetStatus(text );
     } else if( ex.Status == WebExceptionStatus.NameResolutionFailure ) {
         string text = "&eFailed to " + action + ":" +
             Environment.NewLine + "Unable to resolve classicube.net" +
             Environment.NewLine + "you may not be connected to the internet.";
         SetStatus( text );
     } else {
         string text = "&eFailed to " + action + ":" +
             Environment.NewLine + ex.Status;
         SetStatus( text );
     }
 }
开发者ID:Cheesse,项目名称:ClassicalSharp,代码行数:25,代码来源:ClassiCubeScreen.cs


示例20: GetErrorMessage

 static string GetErrorMessage(WebException ex)
 {
     var r = ex.Response as HttpWebResponse;
     return r == null
         ? ex.Message
         : $"{r.StatusCode:d} - {r.Headers["x-error-message"]}";
 }
开发者ID:rackerlabs,项目名称:RackspaceCloudOfficeApiClient,代码行数:7,代码来源:ApiException.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Net.WebHeaderCollection类代码示例发布时间:2022-05-26
下一篇:
C# Net.WebConnectionStream类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap