[ ASP.NET ] Cookie の設定と削除 ( Request.Cookies )

Pocket

ASP.NET において Cookie の設定および削除を行うサンプルコードを掲載しています。まずは、Cookie の一般的な 制限について説明します。説明不要な方はこのセクションは読み飛ばしてください。

スポンサーリンク

Cookie 制限

  • Cookie の有効・無効の設定はブラウザで行うため、WEBサーバーが Cookie を設定してもそれを保存するかどうかは ブラウザ次第である。つまり WEB サーバーは Cookie がブラウザに保存されることを前提にしてはいけない
  • ブラウザでは 全体で少なくとも 300 の Cookie を保存する(RFC2109 より)
  • 少なくとも Cookie 1つにつき 4096 バイトを保存する(RFC2109 より)
  • 一意のホストまたはドメイン名につき少なくとも 20 の Cookie を保存する(RFC2109 より)

RFC2109 では、ブラウザが実装すべき制限が記述されています。上記の制限に合わせて WEB サーバーでは Cookie の数やサイズを考慮すれば多くのブラウザで問題となることは少ないでしょう。

Cookie の設定と取得サンプルコード

ASPX

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Cookie の設定と削除</title>
</head>
<body>

<form id="form1" runat="server">

<div>
     <asp:Button ID="Button1" runat="server" Text="設定" onclick="Button1_Click" />
     <asp:Button ID="Button2" runat="server" Text="削除" onclick="Button2_Click" />
     <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>

</form>
</body>
</html>

VB.NET

Partial Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Label1.Text = String.Empty

        If Not Request.Cookies("userId") Is Nothing Then
            Label1.Text += Server.HtmlEncode(Request.Cookies("userId").Value)
        End If

        If Not Request.Cookies("userName") Is Nothing Then
            Dim cookie As HttpCookie = Request.Cookies("userName")
            Label1.Text += Server.HtmlEncode(cookie.Value)
        End If

    End Sub

    ' Cookie の設定
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click

        ' Cookie 設定方法例1
        Response.Cookies("userId").Value = "UID0001"                  ' Cookie の値
        Response.Cookies("userId").Expires = DateTime.Now.AddDays(10) ' Cookie 有効期間(10日)

        ' Cookie 設定方法例2
        Dim cookie As New HttpCookie("userName")
        cookie.Value = "<まさお>"               ' Cookie の値
        cookie.Expires = DateTime.Now.AddDays(10) ' Cookie 有効期間(10日)

        Response.Cookies.Add(cookie) ' 追加

    End Sub

    ' Cookie の削除
    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click

        ' Cookie 削除例1
        Response.Cookies("userId").Value = "UID0001"                  ' Cookie の値
        Response.Cookies("userId").Expires = DateTime.Now.AddDays(-3) ' Cookie 有効期間(3日前)

        ' Cookie 削除例2
        Dim cookie As New HttpCookie("userName")
        cookie.Value = "<まさお>"               ' Cookie の値
        cookie.Expires = DateTime.Now.AddDays(-3) ' Cookie 有効期間(3日前)

        Response.Cookies.Add(cookie) ' 追加

    End Sub
End Class

C#

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = string.Empty;

        if (Request.Cookies["userId"] != null) {
            Label1.Text += Server.HtmlEncode(Request.Cookies["userId"].Value);
        }

        if (Request.Cookies["userName"] != null) { 
            HttpCookie cookie = Request.Cookies["userName"]; 
            Label1.Text += Server.HtmlEncode(cookie.Value); 
        }
    }

    // Cookie の設定
    protected void Button1_Click(object sender, EventArgs e)
    {
        // Cookie 設定方法例1
        Response.Cookies["userId"].Value = "UID0001";                  // Cookie の値 
        Response.Cookies["userId"].Expires = DateTime.Now.AddDays(10); // Cookie の有効期間(10日)

        // Cookie 設定方法例2
        HttpCookie cookie = new HttpCookie("userName"); 
            
        cookie.Value = "<まさお>";               // Cookie の値
        cookie.Expires = DateTime.Now.AddDays(10);  // Cookie の有効期間(10日)
        Response.Cookies.Add(cookie);
    }

    // Cookie の削除
    protected void Button2_Click(object sender, EventArgs e)
    {
        // Cookie 削除例1
        Response.Cookies["userId"].Value = "UID0001";                  // Cookie の値 
        Response.Cookies["userId"].Expires = DateTime.Now.AddDays(-3); // Cookie の有効期間(3日前)

        // Cookie 削除例2
        HttpCookie cookie = new HttpCookie("userName");

        cookie.Value = "<まさお>";               // Cookie の値
        cookie.Expires = DateTime.Now.AddDays(-3); // Cookie の有効期間(3日前)
        Response.Cookies.Add(cookie);
    }
}

1つの Cookie に複数のキーと値を設定するサンプルコード

次に、1つの Cookie に対して複数のキーと値の組み合わせを設定する場合のサンプルコードです。ユーザーID、ユーザー名、最終アクセス時間などは1つの Cookie にまとめて設定・取得するほうがわかりやすいでしょう。(ただし、Cookie に保存する項目によってはセキュリティ的に問題となる可能性もありますので注意してください)

VB.NET

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Label1.Text = String.Empty
        If Not Request.Cookies("accessUser") Is Nothing Then
            Label1.Text += Server.HtmlEncode(Request.Cookies("accessUser")("userId"))
            Label1.Text += Server.HtmlEncode(Request.Cookies("accessUser")("userName"))
            Label1.Text += Server.HtmlEncode(Request.Cookies("accessUser")("lastAccessTime"))
        End If

    End Sub

    ' Cookie の設定
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click

        ' Cookie 設定方法例1
        Response.Cookies("accessUser")("userId") = "UID0001"                       ' ユーザーID
        Response.Cookies("accessUser")("userName") = "<まさお>"                  ' ユーザー名
        Response.Cookies("accessUser")("lastAccessTime") = DateTime.Now.ToString() ' アクセス時間
        Response.Cookies("accessUser").Expires = DateTime.Now.AddDays(10) ' Cookie 有効期間(10日)

        '' Cookie 設定方法例2
        'Dim cookie As New HttpCookie("accessUser")
        'cookie.Values("userId") = "UID0001"                       ' ユーザーID
        'cookie.Values("userName") = "<まさお>"                  ' ユーザー名
        'cookie.Values("lastAccessTime") = DateTime.Now.ToString() ' アクセス時間
        'cookie.Expires = DateTime.Now.AddDays(10) ' Cookie 有効期間(10日)

        'Response.Cookies.Add(cookie) ' 追加

    End Sub

C#

    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = string.Empty;

        if (Request.Cookies["accessUser"] != null)
        {
            Label1.Text += Server.HtmlEncode(Request.Cookies["accessUser"]["userId"]);
            Label1.Text += Server.HtmlEncode(Request.Cookies["accessUser"]["userName"]);
            Label1.Text += Server.HtmlEncode(Request.Cookies["accessUser"]["lastAccessTime"]);
        }
    }

    // Cookie の設定
    protected void Button1_Click(object sender, EventArgs e)
    {
        // Cookie 設定方法例1
        Response.Cookies["accessUser"]["userId"]         = "UID0001";               // ユーザーID 
        Response.Cookies["accessUser"]["userName"]       = "<まさお>";            // ユーザー名 
        Response.Cookies["accessUser"]["lastAccessTime"] = DateTime.Now.ToString(); // 最終アクセス時間 
        Response.Cookies["accessUser"].Expires = DateTime.Now.AddDays(10); // Cookie の有効期間(10日)

        //// Cookie 設定方法例2
        //HttpCookie cookie = new HttpCookie("accessUser");
        //cookie.Values["userId"] = "UID0001";                     // ユーザーID 
        //cookie.Values["userName"] = "<まさお>";                  // ユーザー名
        //cookie.Values["lastAccessTime"] = DateTime.Now.ToString(); // 最終アクセス時間
        //cookie.Expires = DateTime.Now.AddDays(10);  // Cookie の有効期間(10日)
        //Response.Cookies.Add(cookie);
    }
参考
スポンサーリンク


Pocket

Leave a Comment

Your email address will not be published. Required fields are marked *