Asp.net-managing-state

提供:Dev Guides
移動先:案内検索

ASP.NET-状態の管理

ハイパーテキスト転送プロトコル(HTTP)は、ステートレスプロトコルです。 クライアントがサーバーから切断すると、ASP.NETエンジンはページオブジェクトを破棄します。 このように、各Webアプリケーションは、サーバーメモリを使い果たすことなく、多数の要求を同時に処理するように拡張できます。

ただし、要求間で情報を保存し、必要なときに情報を取得するための手法が必要です。 この情報、つまり、現在のセッションの現在のユーザーのすべてのコントロールと変数の現在の値は、状態と呼ばれます。

ASP.NETは、4種類の状態を管理します。

  • 状態を表示
  • 制御状態
  • セッション状態
  • アプリケーションの状態

状態を表示

ビューステートは、ページとそのすべてのコントロールの状態です。 ASP.NETフレームワークによって投稿間で自動的に維持されます。

ページがクライアントに送り返されると、ページとそのコントロールのプロパティの変更が決定され、_VIEWSTATEという名前の非表示の入力フィールドの値に保存されます。 ページが再びポストバックされると、_VIEWSTATEフィールドがHTTP要求とともにサーバーに送信されます。

ビューステートは、次に対して有効または無効にできます。

  • * web.configファイルの<pages>セクションでEnableViewStateプロパティを設定することにより、アプリケーション全体*。
  • ページ、PageディレクティブのEnableViewState属性を<%@ Page Language = "C#" EnableViewState = "false"%>として設定
  • Control 。Control.EnableViewStateプロパティを設定します。

ビューステートアイテムのコレクションを定義するStateBagクラスによって定義されたビューステートオブジェクトを使用して実装されます。 ステートバッグは、オブジェクトに関連付けられた文字列として保存された属性値のペアを含むデータ構造です。

StateBagクラスには次のプロパティがあります。

Properties Description
Item(name) The value of the view state item with the specified name. This is the default property of the StateBag class.
Count The number of items in the view state collection.
Keys Collection of keys for all the items in the collection.
Values Collection of values for all the items in the collection.

StateBagクラスには次のメソッドがあります。

Methods Description
Add(name, value) Adds an item to the view state collection and existing item is updated.
Clear Removes all the items from the collection.
Equals(Object) Determines whether the specified object is equal to the current object.
Finalize Allows it to free resources and perform other cleanup operations.
GetEnumerator Returns an enumerator that iterates over all the key/value pairs of the StateItem objects stored in the StateBag object.
GetType Gets the type of the current instance.
IsItemDirty Checks a StateItem object stored in the StateBag object to evaluate whether it has been modified.
Remove(name) Removes the specified item.
SetDirty Sets the state of the StateBag object as well as the Dirty property of each of the StateItem objects contained by it.
SetItemDirty Sets the Dirty property for the specified StateItem object in the StateBag object.
ToString Returns a string representing the state bag object.

次の例は、ビューステートを保存する概念を示しています。 ページ上のボタンをクリックしてページがポストバックされるたびにインクリメントされるカウンターを保持しましょう。 ラベルコントロールは、カウンターの値を示します。

マークアップファイルのコードは次のとおりです。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="statedemo._Default" %>

<!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 runat="server">
      <title>
         Untitled Page
      </title>
   </head>

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

         <div>
            <h3>View State demo</h3>

            Page Counter:

            <asp:Label ID="lblCounter" runat="server"/>
            <asp:Button ID="btnIncrement" runat="server" Text="Add Count" onclick="btnIncrement_Click"/>
         </div>

      </form>
   </body>

</html>

この例のコードビハインドファイルは次のとおりです。

public partial class _Default : System.Web.UI.Page
{
   public int counter
   {
      get
      {
         if (ViewState["pcounter"] != null)
         {
            return ((int)ViewState["pcounter"]);
         }
         else
         {
            return 0;
         }
      }

      set
      {
         ViewState["pcounter"] = value;
      }
   }

   protected void Page_Load(object sender, EventArgs e)
   {
      lblCounter.Text = counter.ToString();
      counter++;
   }
}

次の結果が生成されます。

View State Demo

制御状態

制御状態を変更したり、直接アクセスしたり、無効にしたりすることはできません。

セッション状態

ユーザーがASP.NET Webサイトに接続すると、新しいセッションオブジェクトが作成されます。 セッション状態がオンになると、新しいリクエストごとに新しいセッション状態オブジェクトが作成されます。 このセッション状態オブジェクトはコンテキストの一部になり、ページから利用できます。

セッション状態は通常、在庫、サプライヤリスト、顧客レコード、ショッピングカートなどのアプリケーションデータの保存に使用されます。 また、ユーザーとユーザーの設定に関する情報を保持し、保留中の操作を追跡できます。

セッションは、クライアントからサーバーに渡され、Cookieまたは変更されたURLとして返される120ビットのSessionIDで識別および追跡されます。 SessionIDはグローバルに一意でランダムです。

セッション状態オブジェクトは、セッション状態項目のコレクションを定義するHttpSessionStateクラスから作成されます。

HttpSessionStateクラスには、次のプロパティがあります。

Properties Description
SessionID The unique session identifier.
Item(name) The value of the session state item with the specified name. This is the default property of the HttpSessionState class.
Count The number of items in the session state collection.
TimeOut Gets and sets the amount of time, in minutes, allowed between requests before the session-state provider terminates the session.

HttpSessionStateクラスには次のメソッドがあります。

Methods Description
Add(name, value) Adds an item to the session state collection.
Clear Removes all the items from session state collection.
Remove(name) Removes the specified item from the session state collection.
RemoveAll Removes all keys and values from the session-state collection.
RemoveAt Deletes an item at a specified index from the session-state collection.

セッション状態オブジェクトは、セッション状態オブジェクトから情報を保存および取得するための名前と値のペアです。 同じために次のコードを使用できます。

void StoreSessionInfo()
{
   String fromuser = TextBox1.Text;
   Session["fromuser"] = fromuser;
}

void RetrieveSessionInfo()
{
   String fromuser = Session["fromuser"];
   Label1.Text = fromuser;
}

上記のコードは、Session辞書オブジェクトに文字列のみを格納しますが、すべてのプリミティブデータ型とプリミティブデータ型で構成される配列、DataSet、DataTable、HashTable、Imageオブジェクト、および任意のユーザー- ISerializableオブジェクトを継承する定義済みクラス。

次の例は、セッション状態を保存する概念を示しています。 ページには、文字列を入力するテキストボックスと最後のセッションから保存されたテキストを表示するラベルの2つのボタンがあります。

マークアップファイルのコードは次のとおりです。

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default"  %>

<!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 runat="server">
      <title>
         Untitled Page
      </title>
   </head>

   <body>
      <form id="form1" runat="server">
         <div>
            &nbsp; &nbsp; &nbsp;

            <table style="width: 568px; height: 103px">

               <tr>
                  <td style="width: 209px">
                     <asp:Label ID="lblstr" runat="server" Text="Enter a String"  style="width:94px">
                     </asp:Label>
                  </td>

                  <td style="width: 317px">
                     <asp:TextBox ID="txtstr" runat="server" style="width:227px">
                     </asp:TextBox>
                  </td>
               </tr>

               <tr>
                  <td style="width: 209px"> </td>
                  <td style="width: 317px"> </td>
               </tr>

               <tr>
                  <td style="width: 209px">
                     <asp:Button ID="btnnrm" runat="server"
                        Text="No action button" style="width:128px"/>
                  </td>

                  <td style="width: 317px">
                     <asp:Button ID="btnstr" runat="server"
                        OnClick="btnstr_Click" Text="Submit the String"/>
                  </td>
               </tr>

               <tr>
                  <td style="width: 209px">  </td>

                  <td style="width: 317px">  </td>
               </tr>

               <tr>
                  <td style="width: 209px">
                     <asp:Label ID="lblsession" runat="server"  style="width:231px"  >
                     </asp:Label>
                  </td>

                  <td style="width: 317px">  </td>
               </tr>

               <tr>
                  <td style="width: 209px">
                     <asp:Label ID="lblshstr" runat="server">
                     </asp:Label>
                  </td>

                  <td style="width: 317px">  </td>
               </tr>

            </table>

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

デザインビューでは、次のようになります。

セッションデザインビュー

コードビハインドファイルは次のとおりです。

public partial class _Default : System.Web.UI.Page
{
   String mystr;

   protected void Page_Load(object sender, EventArgs e)
   {
      this.lblshstr.Text = this.mystr;
      this.lblsession.Text = (String)this.Session["str"];
   }

   protected void btnstr_Click(object sender, EventArgs e)
   {
      this.mystr = this.txtstr.Text;
      this.Session["str"] = this.txtstr.Text;
      this.lblshstr.Text = this.mystr;
      this.lblsession.Text = (String)this.Session["str"];
   }
}

ファイルを実行し、その動作を観察します。

セッション実行ビュー

アプリケーションの状態

ASP.NETアプリケーションは、Webサーバー上の単一の仮想ディレクトリ内にあるすべてのWebページ、コード、およびその他のファイルのコレクションです。 情報がアプリケーション状態で保存されると、すべてのユーザーが利用できます。

アプリケーション状態の使用を提供するために、ASP.NETはHTTPApplicationStateクラスから各アプリケーションのアプリケーション状態オブジェクトを作成し、このオブジェクトをサーバーメモリに保存します。 このオブジェクトは、クラスファイルglobal.asaxで表されます。

アプリケーション状態は、主にヒットカウンターやその他の統計データ、税率、割引率などのグローバルアプリケーションデータを格納するために使用されます。 サイトにアクセスしたユーザーを追跡するため。

HttpApplicationStateクラスには、次のプロパティがあります。

Properties Description
Item(name) The value of the application state item with the specified name. This is the default property of the HttpApplicationState class.
Count The number of items in the application state collection.

HttpApplicationStateクラスには次のメソッドがあります。

Methods Description
Add(name, value) Adds an item to the application state collection.
Clear Removes all the items from the application state collection.
Remove(name) Removes the specified item from the application state collection.
RemoveAll Removes all objects from an HttpApplicationState collection.
RemoveAt Removes an HttpApplicationState object from a collection by index.
Lock() Locks the application state collection so only the current user can access it.
Unlock() Unlocks the application state collection so all the users can access it.

一般に、アプリケーションの状態データは、イベントのハンドラーを記述することで維持されます。

  • Application_Start
  • Application_End
  • アプリケーションエラー
  • Session_Start
  • Session_End

次のコードスニペットは、アプリケーションの状態情報を保存するための基本的な構文を示しています。

Void Application_Start(object sender, EventArgs e)
{
   Application["startMessage"] = "The application has started.";
}

Void Application_End(object sender, EventArgs e)
{
   Application["endtMessage"] = "The application has ended.";
}