本文整理汇总了C#中System.Net.WebException类的典型用法代码示例。如果您正苦于以下问题:C# WebException类的具体用法?C# WebException怎么用?C# WebException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
WebException类属于System.Net命名空间,在下文中一共展示了WebException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
示例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");
}
示例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));
}
示例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));
}
示例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;
}
示例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;
}
示例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)
{
}
}
}
}
示例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;
}
示例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;
}
示例11: IsNetworkUnavailableFrom
public static bool IsNetworkUnavailableFrom(WebException e)
{
return IsNetworkApproximatelyUnavailable () ||
e.Status == WebExceptionStatus.NameResolutionFailure ||
e.Status == WebExceptionStatus.Timeout ||
e.Status == WebExceptionStatus.ConnectFailure;
}
示例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));
}
示例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;
}
}
示例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);
}
}
示例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));
}