HttpException Construtores
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Inicializa uma nova instância da HttpException classe.
Sobrecargas
| Name | Description |
|---|---|
| HttpException() |
Inicializa uma nova instância da HttpException classe e cria um objeto vazio HttpException . |
| HttpException(String) |
Inicializa uma nova instância da HttpException classe usando uma mensagem de erro fornecida. |
| HttpException(Int32, String) |
Inicializa uma nova instância da HttpException classe usando um código de estado de resposta HTTP e uma mensagem de erro. |
| HttpException(SerializationInfo, StreamingContext) |
Inicializa uma nova instância da HttpException classe com dados serializados. |
| HttpException(String, Exception) |
Inicializa uma nova instância da HttpException classe usando uma mensagem de erro e a InnerException propriedade. |
| HttpException(String, Int32) |
Inicializa uma nova instância da HttpException classe usando uma mensagem de erro e um código de exceção. |
| HttpException(Int32, String, Exception) |
Inicializa uma nova instância da HttpException classe usando um código de estado de resposta HTTP, uma mensagem de erro e a InnerException propriedade. |
| HttpException(Int32, String, Int32) |
Inicializa uma nova instância da HttpException classe usando um código de estado de resposta HTTP, uma mensagem de erro e um código de exceção. |
HttpException()
Inicializa uma nova instância da HttpException classe e cria um objeto vazio HttpException .
public:
HttpException();
public HttpException();
Public Sub New ()
Exemplos
O seguinte exemplo de código demonstra o HttpException construtor da HttpException classe. O CheckNumber método aceita um valor introduzido pelo utilizador através de uma caixa de texto e verifica se é um inteiro. Se o valor não for um inteiro, é lançada uma exceção, e depois é criado e lançado um novo HttpException objeto. Essa exceção é detetada no Button_Click gestor de eventos e a mensagem de erro é exibida no navegador.
Importante
Este exemplo tem uma caixa de texto que aceita a entrada do utilizador, o que constitui uma potencial ameaça à segurança. Por defeito, as páginas Web do ASP.NET validam que a entrada do utilizador não inclui elementos de script ou HTML. Para mais informações, consulte Visão Geral dos Exploits de Scripts.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>
Example for HttpException
</title>
<script language="C#" runat="server">
void CheckNumber()
{
try
{
// Check whether the value is an integer.
String convertInt = textbox1.Text;
Convert.ToInt32(convertInt);
}
catch(Exception e)
{
// Throw a 'HttpException' object.
throw new HttpException();
}
}
void Button_Click(Object sender, EventArgs e)
{
try
{
CheckNumber();
label1.Text = "The integer value you entered is: "+textbox1.Text;
}
catch(HttpException exp)
{
label1.Text = "<font color='red'>An HttpException was raised!:"
+ " The value entered in the textbox is not an integer.</font>";
}
}
void page_load(object sender,EventArgs e)
{
label1.Text="";
}
</script>
</head>
<body>
<center>
<h3>
Example for HttpException
</h3>
</center>
<form id="WebForm9" method="post" runat="server">
<center>
<br />
<b>Enter a value in the text box.</b>
<br />
<asp:TextBox Runat="server" ID="textbox1"></asp:TextBox>
<br />
<asp:Button Text="Click Here" OnClick="Button_Click" Runat="server"></asp:Button>
<br />
<b><asp:Label Runat="server" ID="label1"></asp:Label></b>
</center>
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Example for HttpException</title>
<script language="VB" runat="server">
Sub CheckNumber()
Try
' Check whether the value is an integer.
Dim convertInt As [String] = textbox1.Text
Convert.ToInt32(convertInt)
Catch e As Exception
' Throw the 'HttpException' object.
Throw New HttpException()
End Try
End Sub 'CheckNumber
Sub Button_Click(sender As [Object], e As EventArgs)
Try
CheckNumber()
label1.Text = "The integer value you entered is: " + textbox1.Text
Catch exp As HttpException
label1.Text = "<font color='red'>An HttpException was raised!:" _
& " The value entered in the textbox is not an integer</font>"
End Try
End Sub 'Button_Click
Sub Page_Load(sender As [Object], e As EventArgs)
label1.Text=""
End Sub
</script>
</head>
<body>
<center>
<h3>Example for HttpException</h3>
</center>
<form id="WebForm9" method="post" runat="server">
<center>
<b>Enter a value in the text box.</b>
<asp:TextBox Runat="server" ID="textbox1"></asp:TextBox>
<br />
<asp:Button Text="Click Here" OnClick="Button_Click" Runat="server"></asp:Button>
<br />
<b><asp:Label Runat="server" ID="label1"></asp:Label></b>
</center>
</form>
</body>
</html>
Observações
Ao lidar com exceções, pode ser útil capturar uma série de exceções relacionadas, sendo a exceção externa lançada em resposta a uma exceção interna.
Uma referência à exceção interna que causou a exceção exterior está disponível a partir da InnerException propriedade da exceção exterior. Este mecanismo preserva a informação de erro que é transportada por exceções anteriores, incluindo as originais, permitindo ao mesmo tempo que crie exceções externas mais significativas. Para obter mais informações, veja InnerException.
Ver também
Aplica-se a
HttpException(String)
Inicializa uma nova instância da HttpException classe usando uma mensagem de erro fornecida.
public:
HttpException(System::String ^ message);
public HttpException(string message);
new System.Web.HttpException : string -> System.Web.HttpException
Public Sub New (message As String)
Parâmetros
- message
- String
A mensagem de erro é apresentada ao cliente quando a exceção é lançada.
Exemplos
O seguinte exemplo de código demonstra o HttpException construtor da HttpException classe. An HttpException é lançado se um valor introduzido pelo utilizador for 0.
Importante
Este exemplo tem uma caixa de texto que aceita a entrada do utilizador, o que constitui uma potencial ameaça à segurança. Por defeito, as páginas Web do ASP.NET validam que a entrada do utilizador não inclui elementos de script ou HTML. Para mais informações, consulte Visão Geral dos Exploits de Scripts.
if (Num == 0)
{
throw new HttpException("No value entered");
}
If Num = 0 Then
Throw New HttpException("No value entered")
end if
Ver também
Aplica-se a
HttpException(Int32, String)
Inicializa uma nova instância da HttpException classe usando um código de estado de resposta HTTP e uma mensagem de erro.
public:
HttpException(int httpCode, System::String ^ message);
public HttpException(int httpCode, string message);
new System.Web.HttpException : int * string -> System.Web.HttpException
Public Sub New (httpCode As Integer, message As String)
Parâmetros
- httpCode
- Int32
O código de estado da resposta HTTP enviado ao cliente correspondente a este erro.
- message
- String
A mensagem de erro é apresentada ao cliente quando a exceção é lançada.
Ver também
Aplica-se a
HttpException(SerializationInfo, StreamingContext)
Inicializa uma nova instância da HttpException classe com dados serializados.
protected:
HttpException(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected HttpException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
new System.Web.HttpException : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Web.HttpException
Protected Sub New (info As SerializationInfo, context As StreamingContext)
Parâmetros
- info
- SerializationInfo
O SerializationInfo que contém os dados serializados do objeto sobre a exceção lançada.
- context
- StreamingContext
O StreamingContext que contém a informação contextual sobre a origem ou destino.
Observações
O HttpException construtor é chamado durante a desserialização para reconstituir o objeto exceção que é transmitido através de um fluxo. Para mais informações, consulte XML e Serialização SOAP.
Ver também
Aplica-se a
HttpException(String, Exception)
Inicializa uma nova instância da HttpException classe usando uma mensagem de erro e a InnerException propriedade.
public:
HttpException(System::String ^ message, Exception ^ innerException);
public HttpException(string message, Exception innerException);
new System.Web.HttpException : string * Exception -> System.Web.HttpException
Public Sub New (message As String, innerException As Exception)
Parâmetros
- message
- String
A mensagem de erro é apresentada ao cliente quando a exceção é lançada.
- innerException
- Exception
O InnerException, se houver, que levantou a exceção atual.
Exemplos
O seguinte exemplo de código demonstra o HttpException construtor da HttpException classe. O CheckNumber método aceita um valor introduzido pelo utilizador através de uma caixa de texto e verifica se é um inteiro. Se o valor não for um inteiro, é lançada uma exceção, e depois, no bloco de captura, é criado e lançado um novo HttpException objeto. Essa exceção é detetada no Button_Click gestor de eventos e a mensagem de erro é exibida no navegador.
Importante
Este exemplo tem uma caixa de texto que aceita a entrada do utilizador, o que constitui uma potencial ameaça à segurança. Por defeito, as páginas Web do ASP.NET validam que a entrada do utilizador não inclui elementos de script ou HTML. Para mais informações, consulte Visão Geral dos Exploits de Scripts.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Example for HttpException</title>
<script language="C#" runat="server">
void CheckNumber()
{
try
{
// Check whether the value is an integer.
String convertInt= textbox1.Text;
Convert.ToInt32(convertInt);
}
catch(Exception e)
{
// Throw an HttpException object with a message.
throw new HttpException("THe value entered in the text box is not a integer", e);
}
}
void Button_Click(Object sender, EventArgs e)
{
try
{
CheckNumber();
label1.Text = "The integer value you entered is: " + textbox1.Text;
}
catch(HttpException exp)
{
// Display the exception thrown.
label1.Text = "<font color='red'>An HttpException was raised: " + exp.Message + "</font>";
Exception myInnerException = exp.InnerException;
label2.Text = "InnerException is : " + myInnerException.GetType();
}
}
void page_load(Object sender,EventArgs e)
{
label1.Text="";
label2.Text="";
}
</script>
</head>
<body>
<center>
<h3>Example for HttpException</h3>
</center>
<form id="Form1" method="post" runat="server">
<center>
<b>Enter the value in the text box </b>
<br />
<asp:TextBox Runat="server" ID="textbox1"></asp:TextBox>
<br />
<asp:Button Text="Click Here" OnClick="Button_Click" Runat="server" ID="Button1"></asp:Button>
<br />
<b>
<asp:Label Runat="server" ID="label1"></asp:Label>
<br />
<asp:Label Runat="server" ID="label2"></asp:Label>
</b>
</center>
</form>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Example for HttpException</title>
<script language="VB" runat="server">
Sub CheckNumber()
Try
' Check whether the value is an integer.
Dim convertInt As [String] = textbox1.Text
Convert.ToInt32(convertInt)
Catch e As Exception
' Throw an HttpException object with a message.
Throw New HttpException("The value entered in the textbox is not a integer", e)
End Try
End Sub 'CheckNumber
Sub Button_Click(sender As [Object], e As EventArgs)
Try
CheckNumber()
label1.Text = "The integer value you entered is: " + textbox1.Text
Catch exp As HttpException
' Display the exception thrown.
label1.Text = "<font color='red'>An HttpException was raised!: " + exp.Message + "</font>"
Dim myInnerException As Exception = exp.InnerException
label2.Text = "InnerException is : " + myInnerException.GetType().ToString()
End Try
End Sub 'Button_Click
Sub page_load(sender As [Object], e As EventArgs)
label1.Text=""
label2.Text=""
End Sub
</script>
</head>
<body>
<center>
<h3>Example for HttpException</h3>
<form id="WebForm9" method="post" runat="server">
<b>Enter the value in the text box </b>
<asp:TextBox Runat="server" ID="textbox1"></asp:TextBox>
<br />
<asp:Button Text="Click Here" OnClick="Button_Click" Runat="server" ID="Button1"></asp:Button>
<br />
<b>
<asp:Label Runat="server" ID="label1"></asp:Label>
<br />
<asp:Label Runat="server" ID="label2"></asp:Label>
</b>
</form>
</center>
</body>
</html>
Observações
Ao lidar com exceções, pode ser útil capturar uma série de exceções relacionadas, sendo a exceção externa lançada em resposta a uma exceção interna.
Uma referência à exceção interna que causou a exceção exterior está disponível a partir da InnerException propriedade da exceção exterior. Este mecanismo preserva a informação de erro que é transportada por exceções anteriores, incluindo as originais, permitindo ao mesmo tempo que crie exceções externas mais significativas. Para obter mais informações, veja InnerException.
Ver também
Aplica-se a
HttpException(String, Int32)
Inicializa uma nova instância da HttpException classe usando uma mensagem de erro e um código de exceção.
public:
HttpException(System::String ^ message, int hr);
public HttpException(string message, int hr);
new System.Web.HttpException : string * int -> System.Web.HttpException
Public Sub New (message As String, hr As Integer)
Parâmetros
- message
- String
A mensagem de erro é apresentada ao cliente quando a exceção é lançada.
- hr
- Int32
O código de exceção que define o erro.
Exemplos
O seguinte exemplo de código demonstra o HttpException construtor da HttpException classe. É lançada uma HttpException exceção se um valor introduzido pelo utilizador for 0.
Importante
Este exemplo tem uma caixa de texto que aceita a entrada do utilizador, o que constitui uma potencial ameaça à segurança. Por defeito, as páginas Web do ASP.NET validam que a entrada do utilizador não inclui elementos de script ou HTML. Para mais informações, consulte Visão Geral dos Exploits de Scripts.
if (Num == 0)
{
throw new HttpException("No value entered", 100);
}
If Num = 0 Then
Throw New HttpException("No value entered", 100)
end if
Ver também
Aplica-se a
HttpException(Int32, String, Exception)
Inicializa uma nova instância da HttpException classe usando um código de estado de resposta HTTP, uma mensagem de erro e a InnerException propriedade.
public:
HttpException(int httpCode, System::String ^ message, Exception ^ innerException);
public HttpException(int httpCode, string message, Exception innerException);
new System.Web.HttpException : int * string * Exception -> System.Web.HttpException
Public Sub New (httpCode As Integer, message As String, innerException As Exception)
Parâmetros
- httpCode
- Int32
O código de estado da resposta HTTP é exibido no cliente.
- message
- String
A mensagem de erro é apresentada ao cliente quando a exceção é lançada.
- innerException
- Exception
O InnerException, se houver, que levantou a exceção atual.
Exemplos
O seguinte exemplo de código demonstra o HttpException construtor da HttpException classe. O CheckNumber método aceita um valor inserido pelo utilizador e verifica se este é um inteiro. Se o valor não for um inteiro, é lançada uma exceção, e depois cria-se um novo HttpException objeto contendo o código de estado da resposta HTTP, a mensagem da exceção e qualquer exceção interna. Essa exceção é apanhada no Button_Click gestor de eventos e a mensagem de erro, o código de erro e a exceção interna são exibidos.
Importante
Este exemplo tem uma caixa de texto que aceita a entrada do utilizador, o que constitui uma potencial ameaça à segurança. Por defeito, as páginas Web do ASP.NET validam que a entrada do utilizador não inclui elementos de script ou HTML. Para mais informações, consulte Visão Geral dos Exploits de Scripts.
<%@ Import Namespace="System.Drawing" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Example for HttpException</title>
<script language="C#" runat="server">
void CheckNumber()
{
try
{
// Check whether the value is an integer.
String convertInt = textbox1.Text;
Convert.ToInt32(convertInt);
}
catch(Exception ex)
{
// Throw an HttpException object that contains the HTTP error code,
// message, and inner exception.
throw new HttpException(500, "The entered value is not an integer.", ex);
}
}
void Button_Click(Object sender, EventArgs e)
{
try
{
CheckNumber();
label1.Text = "The integer value you entered is: " + textbox1.Text;
}
catch(HttpException exp)
{
// Display the exception thrown.
label1.ForeColor = Color.Red;
label1.Text = "An HttpException was raised!: " + exp.Message;
Exception myInnerException = exp.InnerException;
// Display the inner exception.
label2.Text = "The InnerException is : " + myInnerException.GetType();
}
}
void page_load(Object sender,EventArgs e)
{
label1.Text="";
label2.Text="";
}
</script>
</head>
<body>
<center>
<h3>Example for HttpException</h3>
<form id="WebForm9" method="post" runat="server">
<b>Enter the value in the text box </b>
<br />
<asp:TextBox Runat="server" ID="textbox1"></asp:TextBox>
<br />
<asp:Button Text="Click Here" OnClick="Button_Click" Runat="server" ID="Button1"></asp:Button>
<br />
<b>
<asp:Label Runat="server" ID="label1"></asp:Label>
<br />
<asp:Label Runat="server" ID="label2"></asp:Label>
</b>
</form>
</center>
</body>
</html>
<%@ Import Namespace="System.Drawing" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Example for HttpException</title>
<script language="VB" runat="server">
Sub CheckNumber()
Try
'Check whether the value is integer.
Dim convertInt As [String] = textbox1.Text
Convert.ToInt32(convertInt)
Catch ex As Exception
' Throw an HttpException object that contains the HTTP error code,
' message, and inner exception.
Throw New HttpException(500, "The entered value is not an integer.", ex)
End Try
End Sub
Sub Button_Click(sender As [Object], e As EventArgs)
Try
CheckNumber()
label1.Text = "The integer Value you entered is: " & textbox1.Text
Catch exp As HttpException
' Display the Exception thrown.
label1.ForeColor = Color.Red
label1.Text = "An HttpException was raised: " & exp.Message
Dim myInnerException As Exception = exp.InnerException
' Display the inner exception.
label2.Text = "InnerException is : " & myInnerException.GetType().ToString()
End Try
End Sub
Sub page_load(sender As [Object], e As EventArgs)
label1.Text = ""
label2.Text = ""
End Sub
</script>
</head>
<body>
<center>
<h3>Example for HttpException</h3>
<form id="WebForm9" method="post" runat="server">
<b>Enter the value in the text box.</b>
<asp:TextBox Runat="server" ID="textbox1"></asp:TextBox>
<br />
<asp:Button Text="Click Here" OnClick="Button_Click" Runat="server" ID="Button1"></asp:Button>
<br />
<b>
<asp:Label Runat="server" ID="label1"></asp:Label>
<br />
<asp:Label Runat="server" ID="label2"></asp:Label>
</b>
</form>
</center>
</body>
</html>
Observações
Ao lidar com exceções, pode ser útil capturar uma série de exceções relacionadas, sendo a exceção externa lançada em resposta a uma exceção interna.
Uma referência à exceção interna que causou a exceção exterior está disponível a partir da InnerException propriedade da exceção exterior. Este mecanismo preserva a informação de erro que é transportada por exceções anteriores, incluindo as originais, permitindo ao mesmo tempo que crie exceções externas mais significativas. Para obter mais informações, veja InnerException.
Ver também
Aplica-se a
HttpException(Int32, String, Int32)
Inicializa uma nova instância da HttpException classe usando um código de estado de resposta HTTP, uma mensagem de erro e um código de exceção.
public:
HttpException(int httpCode, System::String ^ message, int hr);
public HttpException(int httpCode, string message, int hr);
new System.Web.HttpException : int * string * int -> System.Web.HttpException
Public Sub New (httpCode As Integer, message As String, hr As Integer)
Parâmetros
- httpCode
- Int32
O código de estado da resposta HTTP é exibido no cliente.
- message
- String
A mensagem de erro é apresentada ao cliente quando a exceção é lançada.
- hr
- Int32
O código de exceção que define o erro.
Exemplos
O seguinte exemplo de código demonstra o HttpException construtor da HttpException classe. O nome de utilizador e as informações de email são introduzidos pelo utilizador nas caixas de texto fornecidas. Se alguma das caixas de texto for deixada em branco, um HttpException objeto é criado e lançado. O código de erro do HttpException é obtido pelo GetHttpCode método e apresentado na página Web.
Importante
Este exemplo tem uma caixa de texto que aceita a entrada do utilizador, o que constitui uma potencial ameaça à segurança. Por defeito, as páginas Web do ASP.NET validam que a entrada do utilizador não inclui elementos de script ou HTML. Para mais informações, consulte Visão Geral dos Exploits de Scripts.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>HttpException Example</title>
<script language="C#" runat="server">
void SubmitButton_Click(Object sender, EventArgs e)
{
try
{
if(Textbox1.Text.Length==0 || Textbox2.Text.Length==0)
{
// Raise an Exception if the username or the emailfield field is empty.
throw new HttpException(901,"User name or email ID not provided.",333);
}
else
{
MyLabel.Text="Hello "+Textbox1.Text+"<br />";
MyLabel.Text+="The Weekly newsletter is mailed to :"+
Textbox2.Text+"<br />";
}
}
catch(HttpException ex)
{
// Display the error code returned by the GetHttpCode method.
MyLabel.Text="<h4><font color=\"red\">The exception is "+
ex.GetHttpCode() +" - "+ ex.Message + "</font></h4>";
}
}
void Page_Load(object sender,EventArgs e)
{
MyLabel.Text="";
}
</script>
</head>
<body>
<form runat="server" id="Form1">
<h3>HttpException Example</h3>
Enter UserName and Email
<br /><br />
UserName :
<asp:TextBox ID="Textbox1" Runat="server"></asp:TextBox>
<br />
Email ID :
<asp:TextBox ID="Textbox2" Runat="server"></asp:TextBox>
<asp:Button ID="Button1" Text="Submit" OnClick="SubmitButton_Click" runat="server" />
<br />
<asp:label id="MyLabel" runat="server" />
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>HttpException Example</title>
<script language="VB" runat="server">
Sub SubmitButton_Click(sender As Object, e As EventArgs)
Try
If Textbox1.Text.Length = 0 Or Textbox2.Text.Length = 0 Then
' Raise an Exception if the username or emailid field is empty.
Throw New HttpException(901, "User name or email ID not provided", 333)
Else
MyLabel.Text = "Hello " & Textbox1.Text & "<br />"
MyLabel.Text += "The Weekly newsletter is mailed to :" & Textbox2.Text & "<br />"
End If
Catch ex As HttpException
' Display the error code returned by the GetHttpCode method.
MyLabel.Text = "<h4><font color=""red"">The exception is " & ex.GetHttpCode() & _
" - " & ex.Message & "</font></h4>"
End Try
End Sub
Sub Page_Load(sender As Object, e As EventArgs)
MyLabel.Text = ""
End Sub
</script>
</head>
<body>
<form runat="server" id="Form1">
<h3>HttpException Example</h3>
Enter User name and Email
<br /><br />
User Name:
<asp:TextBox ID="Textbox1" Runat="server"></asp:TextBox>
<br />
Email ID:
<asp:TextBox ID="Textbox2" Runat="server"></asp:TextBox>
<asp:Button ID="Button1" Text="Submit" OnClick="SubmitButton_Click" runat="server"/>
<br />
<asp:label id="MyLabel" runat="server"/>
</form>
</body>
</html>