Поделиться через


WebException Конструкторы

Определение

Инициализирует новый экземпляр класса WebException.

Перегрузки

Имя Описание
WebException()

Инициализирует новый экземпляр класса WebException.

WebException(String)

Инициализирует новый экземпляр WebException класса с указанным сообщением об ошибке.

WebException(SerializationInfo, StreamingContext)
Устаревшие..

Инициализирует новый экземпляр WebException класса из указанных SerializationInfo и StreamingContext экземпляров.

WebException(String, WebExceptionStatus)

Инициализирует новый экземпляр WebException класса с указанным сообщением об ошибке и состоянием.

WebException(String, Exception)

Инициализирует новый экземпляр WebException класса с указанным сообщением об ошибке и вложенным исключением.

WebException(String, Exception, WebExceptionStatus, WebResponse)

Инициализирует новый экземпляр WebException класса с указанным сообщением об ошибке, вложенным исключением, состоянием и ответом.

WebException()

Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs

Инициализирует новый экземпляр класса WebException.

public:
 WebException();
public WebException();
Public Sub New ()

Примеры

В следующем примере создается исключение по умолчанию WebException.


 try   
 {
     // A 'Socket' object has been created.
     Socket httpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

     // The IPaddress of the unknown uri is resolved using the 'Dns.Resolve' method. 
     
     IPHostEntry hostEntry = Dns.Resolve("http://www.contoso.com");

     IPAddress serverAddress = hostEntry.AddressList[0];
     IPEndPoint endPoint = new IPEndPoint(serverAddress, 80);
     httpSocket.Connect(endPoint);
     Console.WriteLine("Connection created successfully");
     httpSocket.Close();
  }
catch(SocketException e)
  {
  String exp = e.Message;	
  // Throw the WebException with no parameters.
     throw new WebException();
  }
Try
    ' A 'Socket' object has been created.
    Dim httpSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    
    ' The IPaddress of the unknown uri is resolved using the 'Dns.Resolve' method. 
     ' which leads to the 'SocketException' exception. 
    
    Dim hostEntry As IPHostEntry = Dns.Resolve("http://www.contoso.com")
    
    Dim serverAddress As IPAddress = hostEntry.AddressList(0)
    Dim endPoint As New IPEndPoint(serverAddress, 80)
    httpSocket.Connect(endPoint)
    Console.WriteLine("Connection created successfully")
    httpSocket.Close()
Catch e As SocketException
    Dim exp As [String] = e.Message
    ' Throw the WebException with no parameters.
    Throw New WebException()
End Try

Комментарии

Конструктор без параметров инициализирует новый экземпляр WebException класса. Свойство Message инициализируется в системном сообщении, описывающем ошибку. Это сообщение учитывает текущий язык и региональные параметры системы. Response Инициализированы InnerExceptionnullсвойства. Свойство Status инициализируется в RequestCanceled.

Применяется к

WebException(String)

Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs

Инициализирует новый экземпляр WebException класса с указанным сообщением об ошибке.

public:
 WebException(System::String ^ message);
public WebException(string message);
public WebException(string? message);
new System.Net.WebException : string -> System.Net.WebException
Public Sub New (message As String)

Параметры

message
String

Текст сообщения об ошибке.

Примеры

В следующем примере создается WebException исключение, указывая сообщение об ошибке.

 try
{
     // A 'Socket' object has been created.
     Socket httpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

     // The IPaddress of the unknown uri is resolved using the 'Dns.Resolve' method. 
     IPHostEntry hostEntry = Dns.Resolve(connectUri);

     IPAddress serverAddress = hostEntry.AddressList[0];
     IPEndPoint endPoint = new IPEndPoint(serverAddress, 80);
     httpSocket.Connect(endPoint);
     Console.WriteLine("Connection created successfully");
     httpSocket.Close();
  }
catch(SocketException e)
  {		     
     Console.WriteLine("\nException thrown.\nThe Original Message is: "+e.Message);
     // Throw the 'WebException' object with a message string specific to the situation.
     throw new WebException("Unable to locate the Server with 'www.contoso.com' Uri.");
  }

Try
    ' A 'Socket' object has been created.
    Dim httpSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    
    ' The IPaddress of the unknown uri is resolved using the 'Dns.Resolve' method. 
     
    Dim hostEntry As IPHostEntry = Dns.Resolve(connectUri)
    
    Dim serverAddress As IPAddress = hostEntry.AddressList(0)
    Dim endPoint As New IPEndPoint(serverAddress, 80)
    httpSocket.Connect(endPoint)
    Console.WriteLine("Connection created successfully")
    httpSocket.Close()
Catch e As SocketException
    Console.WriteLine((ControlChars.Cr + "Exception thrown." + ControlChars.Cr + "The Original Message is: " + e.Message))
    ' Throw the 'WebException' object with a message string specific to the situation.
    Throw New WebException("Unable to locate the Server with 'www.contoso.com' Uri.")
End Try

Комментарии

Экземпляр WebException инициализирован со свойством, Message заданным значением message. Если message это nullтак, Message свойство инициализируется в предоставленное системой сообщение. Response Инициализированы InnerExceptionnullсвойства. Свойство Status инициализируется в RequestCanceled.

См. также раздел

Применяется к

WebException(SerializationInfo, StreamingContext)

Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs

Внимание

This API supports obsolete formatter-based serialization. It should not be called or extended by application code.

Инициализирует новый экземпляр WebException класса из указанных SerializationInfo и StreamingContext экземпляров.

protected:
 WebException(System::Runtime::Serialization::SerializationInfo ^ serializationInfo, System::Runtime::Serialization::StreamingContext streamingContext);
[System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
protected WebException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
protected WebException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
[<System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
new System.Net.WebException : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Net.WebException
new System.Net.WebException : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Net.WebException
Protected Sub New (serializationInfo As SerializationInfo, streamingContext As StreamingContext)

Параметры

serializationInfo
SerializationInfo

Значение SerializationInfo , содержащее сведения, необходимые для сериализации нового WebException.

streamingContext
StreamingContext

Объект, StreamingContext содержащий источник сериализованного потока, связанного с новым WebException.

Атрибуты

Комментарии

Этот конструктор реализует ISerializable интерфейс для WebException класса.

См. также раздел

Применяется к

WebException(String, WebExceptionStatus)

Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs

Инициализирует новый экземпляр WebException класса с указанным сообщением об ошибке и состоянием.

public:
 WebException(System::String ^ message, System::Net::WebExceptionStatus status);
public WebException(string message, System.Net.WebExceptionStatus status);
public WebException(string? message, System.Net.WebExceptionStatus status);
new System.Net.WebException : string * System.Net.WebExceptionStatus -> System.Net.WebException
Public Sub New (message As String, status As WebExceptionStatus)

Параметры

message
String

Текст сообщения об ошибке.

status
WebExceptionStatus

Одно из значений WebExceptionStatus .

Примеры

В следующем примере создается WebException исключение, указывающее сообщение об ошибке и сообщение об ошибке WebExceptionStatus.


 try
{
       // A 'Socket' object has been created.
       Socket httpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

      // The IPaddress of the unknown uri is resolved using the 'Dns.Resolve' method. 
  
      IPHostEntry hostEntry = Dns.Resolve("http://www.contoso.com");

      IPAddress serverAddress = hostEntry.AddressList[0];
      IPEndPoint endPoint = new IPEndPoint(serverAddress, 80);
      httpSocket.Connect(endPoint);
      Console.WriteLine("Connection created successfully");
      httpSocket.Close();
   }
catch(SocketException e)
  {
      Console.WriteLine("\nException thrown.\nThe Original Message is: "+e.Message);
      // Throw the 'WebException' object with a message string and message status specific to the situation.
      throw new WebException("Unable to locate the Server with 'www.contoso.com' Uri.",WebExceptionStatus.NameResolutionFailure);
  }

Try
    ' A 'Socket' object has been created.
    Dim httpSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    
    ' The IPaddress of the unknown uri is resolved using the 'Dns.Resolve' method. 
     
    Dim hostEntry As IPHostEntry = Dns.Resolve(connectUri)
    
    Dim serverAddress As IPAddress = hostEntry.AddressList(0)
    Dim endPoint As New IPEndPoint(serverAddress, 80)
    httpSocket.Connect(endPoint)
    Console.WriteLine("Connection created successfully")
    httpSocket.Close()
Catch e As SocketException
    Console.WriteLine((ControlChars.Cr + "Exception thrown." + ControlChars.Cr + "The Original Message is: " + e.Message))
    ' Throw the 'WebException' object with a message string and message status specific to the situation.
    Throw New WebException("Unable to locate the Server with 'www.contoso.com' Uri.", WebExceptionStatus.NameResolutionFailure)
End Try

Комментарии

WebException Экземпляр инициализирован со свойствомMessage, заданным значениемmessage, а Status свойство имеет значение status. Если message это nullтак, Message свойство инициализируется в предоставленное системой сообщение. Response Инициализированы InnerExceptionnullсвойства.

Применяется к

WebException(String, Exception)

Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs

Инициализирует новый экземпляр WebException класса с указанным сообщением об ошибке и вложенным исключением.

public:
 WebException(System::String ^ message, Exception ^ inner);
public:
 WebException(System::String ^ message, Exception ^ innerException);
public WebException(string message, Exception inner);
public WebException(string? message, Exception? innerException);
public WebException(string message, Exception innerException);
new System.Net.WebException : string * Exception -> System.Net.WebException
new System.Net.WebException : string * Exception -> System.Net.WebException
Public Sub New (message As String, inner As Exception)
Public Sub New (message As String, innerException As Exception)

Параметры

message
String

Текст сообщения об ошибке.

innerinnerException
Exception

Вложенное исключение.

Примеры

В следующем примере создается исключение WebException , указывающее сообщение об ошибке и вложенное исключение.


   try
   {
          // A 'Socket' object has been created.
          Socket httpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

          // The IPaddress of the unknown uri is resolved using the 'Dns.Resolve' method. 
       
          IPHostEntry hostEntry = Dns.Resolve(connectUri);

          IPAddress serverAddress = hostEntry.AddressList[0];
          IPEndPoint endPoint = new IPEndPoint(serverAddress, 80);
          httpSocket.Connect(endPoint);
          Console.WriteLine("Connection created successfully");
          httpSocket.Close();		 
    }
  catch(SocketException e)
{ 
       Console.WriteLine("\nException thrown.\nThe Original Message is: "+e.Message);
       //  Throw the 'WebException' object with a message string specific to the situation; 
          //  and the 'InnerException' which actually lead to this exception.
          throw new WebException("Unable to locate the Server with 'www.contoso.com' Uri.",e);
    }

Try
    ' A 'Socket' object has been created.
    Dim httpSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    
    ' The IPaddress of the unknown uri is resolved using the 'Dns.Resolve' method. 
     Dim hostEntry As IPHostEntry = Dns.Resolve(connectUri)
    
    Dim serverAddress As IPAddress = hostEntry.AddressList(0)
    Dim endPoint As New IPEndPoint(serverAddress, 80)
    httpSocket.Connect(endPoint)
    Console.WriteLine("Connection created successfully")
    httpSocket.Close()
Catch e As SocketException
    Console.WriteLine((ControlChars.Cr + "Exception thrown." + ControlChars.Cr + "The Original Message is: " + e.Message))
    ' Throw the 'WebException' object with a message string specific to the situation. 
     ' and the 'InnerException' which actually lead to this exception.
    Throw New WebException("Unable to locate the Server with 'www.contoso.com' Uri.", e)
End Try

Комментарии

WebException Экземпляр инициализирован со свойствомMessage, заданным значениемmessage, а InnerException свойство имеет значение innerException. Если message это nullтак, Message свойство инициализируется в предоставленное системой сообщение. Response Инициализированы InnerExceptionnullсвойства. Свойство Status инициализируется в RequestCanceled.

См. также раздел

Применяется к

WebException(String, Exception, WebExceptionStatus, WebResponse)

Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs
Исходный код:
WebException.cs

Инициализирует новый экземпляр WebException класса с указанным сообщением об ошибке, вложенным исключением, состоянием и ответом.

public:
 WebException(System::String ^ message, Exception ^ inner, System::Net::WebExceptionStatus status, System::Net::WebResponse ^ response);
public:
 WebException(System::String ^ message, Exception ^ innerException, System::Net::WebExceptionStatus status, System::Net::WebResponse ^ response);
public WebException(string message, Exception inner, System.Net.WebExceptionStatus status, System.Net.WebResponse response);
public WebException(string? message, Exception? innerException, System.Net.WebExceptionStatus status, System.Net.WebResponse? response);
public WebException(string message, Exception innerException, System.Net.WebExceptionStatus status, System.Net.WebResponse response);
new System.Net.WebException : string * Exception * System.Net.WebExceptionStatus * System.Net.WebResponse -> System.Net.WebException
new System.Net.WebException : string * Exception * System.Net.WebExceptionStatus * System.Net.WebResponse -> System.Net.WebException
Public Sub New (message As String, inner As Exception, status As WebExceptionStatus, response As WebResponse)
Public Sub New (message As String, innerException As Exception, status As WebExceptionStatus, response As WebResponse)

Параметры

message
String

Текст сообщения об ошибке.

innerinnerException
Exception

Вложенное исключение.

status
WebExceptionStatus

Одно из значений WebExceptionStatus .

response
WebResponse

WebResponse Экземпляр, содержащий ответ удаленного узла.

Примеры

В следующем примере создается WebException исключение, указывающее сообщение об ошибке и сообщение об ошибке WebExceptionStatus.

      // Send the data. 
      Encoding ASCII = Encoding.ASCII;
      string requestPage = "GET /nhjj.htm HTTP/1.1\r\nHost: " + connectUri + "\r\nConnection: Close\r\n\r\n";
      Byte[] byteGet = ASCII.GetBytes(requestPage);
      Byte[] recvBytes = new Byte[256];

      // Create an 'IPEndPoint' object.
 
      IPHostEntry hostEntry = Dns.Resolve(connectUri);
      IPAddress serverAddress = hostEntry.AddressList[0];
      IPEndPoint endPoint = new IPEndPoint(serverAddress, 80);

      // Create a 'Socket' object  for sending data.
      Socket connectSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
 
      // Connect to host using 'IPEndPoint' object.

      connectSocket.Connect(endPoint);
 
      // Sent the 'requestPage' text to the host.
      connectSocket.Send(byteGet, byteGet.Length, 0);
 
      // Receive the information sent by the server.
      Int32 bytesReceived = connectSocket.Receive(recvBytes, recvBytes.Length, 0);
      String headerString = ASCII.GetString(recvBytes, 0, bytesReceived);

     // Check whether 'status 404' is there or not in the information sent by server.
     if(headerString.IndexOf("404")!=-1)
     {	 
         bytesReceived = connectSocket.Receive(recvBytes, recvBytes.Length, 0);
         MemoryStream memoryStream = new MemoryStream(recvBytes);
         getStream = (Stream) memoryStream;
 
         // Create a 'WebResponse' object
         WebResponse myWebResponse = (WebResponse) new HttpConnect(getStream);
         Exception myException = new Exception("File Not found");

         // Throw the 'WebException' object with a message string, message status,InnerException and WebResponse
         throw new WebException("The Requested page is not found.",myException,WebExceptionStatus.ProtocolError,myWebResponse);
     }

     connectSocket.Close();

     ' Send the data. 
       Dim ASCII As Encoding = Encoding.ASCII
       Dim requestPage As String = "GET /nhjj.htm HTTP/1.1" + ControlChars.Lf + ControlChars.Cr + "Host: " + connectUri + ControlChars.Lf + ControlChars.Cr + "Connection: Close" + ControlChars.Lf + ControlChars.Cr + ControlChars.Lf + ControlChars.Cr
       Dim byteGet As [Byte]() = ASCII.GetBytes(requestPage)
       Dim recvBytes(256) As [Byte]
       
       ' Create an 'IPEndPoint' object.
       Dim hostEntry As IPHostEntry = Dns.Resolve(connectUri)
       Dim serverAddress As IPAddress = hostEntry.AddressList(0)
       Dim endPoint As New IPEndPoint(serverAddress, 80)
       
       ' Create a 'Socket' object  for sending data.
       Dim connectSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
       
       ' Connect to host using 'IPEndPoint' object.
       connectSocket.Connect(endPoint)
       
       ' Sent the 'requestPage' text to the host.
       connectSocket.Send(byteGet, byteGet.Length, 0)
       
       ' Receive the information sent by the server.
       Dim bytesReceived As Int32 = connectSocket.Receive(recvBytes, recvBytes.Length, 0)
       Dim headerString As [String] = ASCII.GetString(recvBytes, 0, bytesReceived)
      
       ' Check whether 'status 404' is there or not in the information sent by server.
       If headerString.IndexOf("404") <> False Then
           bytesReceived = connectSocket.Receive(recvBytes, recvBytes.Length, 0)
           Dim memoryStream As New MemoryStream(recvBytes)
           getStream = CType(memoryStream, Stream)
           
           ' Create a 'WebResponse' object.
           Dim myWebResponse As WebResponse = CType(New HttpConnect(getStream), WebResponse)
           Dim myException As New Exception("File Not found")
           
           ' Throw the 'WebException' object with a message string, message status,InnerException and WebResponse.
           Throw New WebException("The Requested page is not found.", myException, WebExceptionStatus.ProtocolError, myWebResponse)
       End If 

       connectSocket.Close()

Комментарии

WebException Экземпляр инициализируется свойствомmessageMessage, заданным значением, свойством, InnerException заданным innerExceptionзначением, Status свойством, заданным значениемstatus, и Response свойством, заданным значениемresponse. Если message это nullтак, Message свойство инициализируется в предоставленное системой сообщение.

Применяется к