HttpCookie HttpCookie HttpCookie HttpCookie Class

Definición

Proporciona un método con seguridad de tipos para crear y manipular cookies HTTP individuales.Provides a type-safe way to create and manipulate individual HTTP cookies.

public ref class HttpCookie sealed
public sealed class HttpCookie
type HttpCookie = class
Public NotInheritable Class HttpCookie
Herencia
HttpCookieHttpCookieHttpCookieHttpCookie

Ejemplos

En el ejemplo de código siguiente se muestra cómo comprobar una cookie DateCookieExample denominada en HttpRequest el objeto.The following code example demonstrates how to check for a cookie named DateCookieExample in the HttpRequest object. Si no se encuentra la cookie, se crea y se agrega al HttpResponse objeto.If the cookie is not found, it is created and added to the HttpResponse object. La cookie se establece para que expire en 10 minutos.The cookie is set to expire in 10 minutes.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        // Get cookie from the current request.
        HttpCookie cookie = Request.Cookies.Get("DateCookieExample");
        
        // Check if cookie exists in the current request.
        if (cookie == null)
        {
            sb.Append("Cookie was not received from the client. ");
            sb.Append("Creating cookie to add to the response. <br/>");
            // Create cookie.
            cookie = new HttpCookie("DateCookieExample");
            // Set value of cookie to current date time.
            cookie.Value = DateTime.Now.ToString();
            // Set cookie to expire in 10 minutes.
            cookie.Expires = DateTime.Now.AddMinutes(10d);
            // Insert the cookie in the current HttpResponse.
            Response.Cookies.Add(cookie);
        }
        else
        {
            sb.Append("Cookie retrieved from client. <br/>");
            sb.Append("Cookie Name: " + cookie.Name + "<br/>");
            sb.Append("Cookie Value: " + cookie.Value + "<br/>");
            sb.Append("Cookie Expiration Date: " + 
                cookie.Expires.ToString() + "<br/>");
        }
        Label1.Text = sb.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>HttpCookie Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:Label id="Label1" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim sb As New StringBuilder()
        ' Get cookie from current request.
        Dim cookie As HttpCookie
        cookie = Request.Cookies.Get("DateCookieExample")
        
        ' Check if cookie exists in the current request
        If (cookie Is Nothing) Then
            sb.Append("Cookie was not received from the client. ")
            sb.Append("Creating cookie to add to the response. <br/>")
            ' Create cookie.
            cookie = New HttpCookie("DateCookieExample")
            ' Set value of cookie to current date time.
            cookie.Value = DateTime.Now.ToString()
            ' Set cookie to expire in 10 minutes.
            cookie.Expires = DateTime.Now.AddMinutes(10D)
            ' Insert the cookie in the current HttpResponse.
            Response.Cookies.Add(cookie)
        Else
            sb.Append("Cookie retrieved from client. <br/>")
            sb.Append("Cookie Name: " + cookie.Name + "<br/>")
            sb.Append("Cookie Value: " + cookie.Value + "<br/>")
            sb.Append("Cookie Expiration Date: " & _
                cookie.Expires.ToString() & "<br/>")
        End If
        Label1.Text = sb.ToString()

    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>HttpCookie Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:Label id="Label1" runat="server"></asp:Label>    
    </div>
    </form>
</body>
</html>

Comentarios

La HttpCookie clase obtiene y establece las propiedades de cookies individuales.The HttpCookie class gets and sets properties of individual cookies. La HttpCookieCollection clase proporciona métodos para almacenar, recuperar y administrar varias cookies.The HttpCookieCollection class provides methods to store, retrieve, and manage multiple cookies.

ASP.NET incluye dos colecciones de cookies intrínsecas.ASP.NET includes two intrinsic cookie collections. La colección a la que se Cookies tiene acceso a HttpRequest través de la colección del objeto contiene las cookies transmitidas Cookie por el cliente al servidor en el encabezado.The collection accessed through the Cookies collection of the HttpRequest object contains cookies transmitted by the client to the server in the Cookie header. La colección a la que se Cookies tiene acceso a HttpResponse través de la colección del objeto contiene nuevas cookies creadas en el servidor y Set-Cookie transmitidas al cliente en el encabezado de respuesta http.The collection accessed through the Cookies collection of the HttpResponse object contains new cookies created on the server and transmitted to the client in the Set-Cookie HTTP response header.

Constructores

HttpCookie(String) HttpCookie(String) HttpCookie(String) HttpCookie(String)

Crea una nueva cookie y le asigna un nombre.Creates and names a new cookie.

HttpCookie(String, String) HttpCookie(String, String) HttpCookie(String, String) HttpCookie(String, String)

Crea una nueva cookie y le asigna un nombre y un valor.Creates, names, and assigns a value to a new cookie.

Propiedades

Domain Domain Domain Domain

Obtiene o establece el dominio al que se asociará la cookie.Gets or sets the domain to associate the cookie with.

Expires Expires Expires Expires

Obtiene o establece la fecha y la hora de expiración de la cookie.Gets or sets the expiration date and time for the cookie.

HasKeys HasKeys HasKeys HasKeys

Obtiene un valor que indica si una cookie tiene subclaves.Gets a value indicating whether a cookie has subkeys.

HttpOnly HttpOnly HttpOnly HttpOnly

Obtiene o establece un valor que especifica si se puede obtener acceso a una cookie mediante script de cliente.Gets or sets a value that specifies whether a cookie is accessible by client-side script.

Item[String] Item[String] Item[String] Item[String]

Obtiene un acceso directo a la propiedad Values.Gets a shortcut to the Values property. Se proporciona esta propiedad para que exista compatibilidad con versiones anteriores de las páginas Active Server (ASP).This property is provided for compatibility with previous versions of Active Server Pages (ASP).

Name Name Name Name

Obtiene o establece el nombre de una cookie.Gets or sets the name of a cookie.

Path Path Path Path

Obtiene o establece la ruta de acceso virtual que se transmitirá con la cookie actual.Gets or sets the virtual path to transmit with the current cookie.

SameSite SameSite SameSite SameSite

Obtiene o establece el valor del atributo SameSite de la cookie.Gets or sets the value for the SameSite attribute of the cookie.

Secure Secure Secure Secure

Obtiene o establece un valor que indica si se va a transmitir la cookie a través de Secure Sockets Layer (SSL), es decir, sólo a través de HTTPS.Gets or sets a value indicating whether to transmit the cookie using Secure Sockets Layer (SSL)--that is, over HTTPS only.

Shareable Shareable Shareable Shareable

Determina si la cookie puede participar en el almacenamiento en caché de los resultados.Determines whether the cookie is allowed to participate in output caching.

Value Value Value Value

Obtiene o establece un valor de cookie individual.Gets or sets an individual cookie value.

Values Values Values Values

Obtiene una colección de pares de clave/valor que se incluyen en un solo objeto cookie.Gets a collection of key/value pairs that are contained within a single cookie object.

Métodos

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)
TryParse(String, HttpCookie) TryParse(String, HttpCookie) TryParse(String, HttpCookie) TryParse(String, HttpCookie)

Convierte la representación de cadena especificada de una cookie en el objeto HttpCookie equivalente y devuelve un valor que indica si la conversión se realizó correctamente.Converts the specified string representation of a cookie into its HttpCookie equivalent and returns a value that indicates whether the conversion succeeded.

Se aplica a

Consulte también: