WebMethodAttribute.EnableSession Propriedade

Definição

Indica se o estado de sessão é habilitado para um método de serviço Web XML.Indicates whether session state is enabled for an XML Web service method.

public:
 property bool EnableSession { bool get(); void set(bool value); };
public bool EnableSession { get; set; }
member this.EnableSession : bool with get, set
Public Property EnableSession As Boolean

Valor da propriedade

Boolean

true se o estado de sessão é habilitado para um método de serviço Web XML.true if session state is enabled for an XML Web service method. O padrão é false.The default is false.

Exemplos

O exemplo a seguir usa o estado de sessão para determinar quantas vezes uma sessão específica acessa o método XML Web Service SessionHitCounter .The example below uses session state to determine how many times a particular session accesses the XML Web service method SessionHitCounter.

<%@ WebService Language="C#" Class="Util" %>
 
 using System.Web.Services;
 
 public class Util: WebService {
   [ WebMethod(Description="Per session Hit Counter",EnableSession=true)]
    public int SessionHitCounter() {
       if (Session["HitCounter"] == null) {
          Session["HitCounter"] = 1;
       }
       else {
          Session["HitCounter"] = ((int) Session["HitCounter"]) + 1;
          }
       return ((int) Session["HitCounter"]);
    }   
 }
<%@ WebService Language="VB" Class="Util" %>
 
Imports System.Web.Services

Public Class Util
    Inherits WebService
    
    <WebMethod(Description := "Per session Hit Counter", _
        EnableSession := True)> _
    Public Function SessionHitCounter() As Integer
        
        If Session("HitCounter") Is Nothing Then
            Session("HitCounter") = 1
        Else
            Session("HitCounter") = CInt(Session("HitCounter")) + 1
        End If
        Return CInt(Session("HitCounter"))
    End Function
End Class

O exemplo de código a seguir é um cliente Web Forms de um serviço Web XML que usa o estado de sessão.The following code example is a Web Forms client of an XML Web service that uses session state. O cliente persiste o cookie HTTP que identifica exclusivamente a sessão armazenando-a no estado de sessão do cliente.The client persists the HTTP cookie that uniquely identifies the session by storing it in the client's session state.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>

<html>

    <script runat="server">

        void EnterBtn_Click(Object Src, EventArgs E) 
    {
      // Create a new instance of a proxy class for your XML Web service.
      ServerUsage su = new ServerUsage();
          CookieContainer cookieJar;

      // Check to see if the cookies have already been saved for this session.
      if (Session["CookieJar"] == null) 
        cookieJar= new CookieContainer();
          else
       cookieJar = (CookieContainer) Session["CookieJar"];

        // Assign the CookieContainer to the proxy class.
        su.CookieContainer = cookieJar;

      // Invoke an XML Web service method that uses session state and thus cookies.
      int count = su.PerSessionServiceUsage();         

      // Store the cookies received in the session state for future retrieval by this session.
      Session["CookieJar"] = cookieJar;

          // Populate the text box with the results from the call to the XML Web service method.
          SessionCount.Text = count.ToString();  
        }
         
    </script>
    <body>
       <form runat=server ID="Form1">
           
             Click to bump up the Session Counter.
             <p>
             <asp:button text="Bump Up Counter" Onclick="EnterBtn_Click" runat=server ID="Button1" NAME="Button1"/>
             <p>
             <asp:label id="SessionCount"  runat=server/>
          
       </form>
    </body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>

<html>

    <script runat=server>

        Public Sub EnterBtn_Click(src As Object, E As EventArgs) 

      ' Create a new instance of a proxy class for your XML Web service.
      Dim su As ServerUsage = new ServerUsage()
          Dim cookieJar As CookieContainer

      ' Check to see if the cookies have already been saved for this session.
      If (Session("CookieJar") Is Nothing) 
        cookieJar= new CookieContainer()
          Else
       cookieJar = Session("CookieJar")
      End If
   

        ' Assign the CookieContainer to the proxy class.
        su.CookieContainer = cookieJar

      ' Invoke an XML Web service method that uses session state and thus cookies.
      Dim count As Integer = su.PerSessionServiceUsage()         

      ' Store the cookies received in the session state for future retrieval by this session.
      Session("CookieJar") = cookieJar

          ' Populate the text box with the results from the call to the XML Web service method.
          SessionCount.Text = count.ToString()  
    End Sub
         
    </script>
    <body>
       <form runat=server ID="Form1">
           
             Click to bump up the Session Counter.
             <p>
             <asp:button text="Bump Up Counter" Onclick="EnterBtn_Click" runat=server ID="Button1" NAME="Button1"/>
             <p>
             <asp:label id="SessionCount"  runat=server/>
          
       </form>
    </body>
</html>

Comentários

Para armazenar o estado de sessão no objeto ASP.NET HttpSessionState , o serviço Web XML deve herdar de WebService e WebMethodAttribute aplicado ao método de serviço Web XML, definindo a EnableSession propriedade como true .In order to store session state in the ASP.NET HttpSessionState object, the XML Web service must inherit from WebService and a WebMethodAttribute applied to the XML Web service method, setting the EnableSession property to true. Se o estado da sessão não for necessário para um método de serviço Web XML, a desabilitação poderá melhorar o desempenho.If session state is not needed for an XML Web service method, then disabling it may improve performance.

Um cliente de serviço Web XML é identificado exclusivamente por um cookie HTTP retornado por um serviço Web XML.An XML Web service client is uniquely identified by an HTTP cookie returned by an XML Web service. Para que um serviço Web XML Mantenha o estado de sessão para um cliente, o cliente deve manter o cookie.In order for an XML Web service to maintain session state for a client, the client must persist the cookie. Os clientes podem receber o cookie HTTP criando uma nova instância do CookieContainer e atribuindo isso à CookieContainer propriedade da classe proxy antes de chamar o método XML Web Service.Clients can receive the HTTP cookie by creating a new instance of CookieContainer and assigning that to the CookieContainer property of the proxy class before calling the XML Web service method. Se você precisar manter o estado da sessão além de quando a instância da classe proxy sair do escopo, o cliente deverá persistir o cookie HTTP entre as chamadas para o serviço Web XML.If you need to maintain session state beyond when the proxy class instance goes out of scope, the client must persist the HTTP cookie between calls to the XML Web service. Por exemplo, um cliente Web Forms pode persistir o cookie HTTP Salvando o CookieContainer em seu próprio estado de sessão.For instance, a Web Forms client can persist the HTTP cookie by saving the CookieContainer in its own session state. Como nem todos os Web Services XML usam o estado de sessão e, portanto, os clientes nem sempre são obrigados a usar a CookieContainer propriedade de um proxy de cliente, a documentação do serviço Web XML deve indicar se o estado da sessão é usado.Because not all XML Web services use session state and thus clients are not always required to use the CookieContainer property of a client proxy, the documentation for the XML Web service should state whether session state is used.

Aplica-se a

Confira também