Вы находитесь на странице: 1из 16

.

Net Apprentice

Gesto de Estado

Arquitectura de Sistemas
DEI-ISEP

Gesto do estado
Sem gesto de estado
Login.aspx
Please enter your logon information: First Name John Last Name Chen

Com gesto de estado


Login.aspx
Please enter your logon information: First Name John Last Name Chen

Submit Greetings.aspx Hello


I forget who you are!!

Web Server

Submit Greetings.aspx Hello John Chen

Web Server

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

.Net Apprentice

Application Life Cycle


When ASP.NET receives the first request for any resource in an application, a class named ApplicationManager creates an application domain. Application domains provide isolation between applications for global variables and allow each application to be unloaded separately. Within an application domain, an instance of the class named HostingEnvironment is created, Provides applicationmanagement functions and application services to a managed application within its application domain.

Application Life Cycle

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

.Net Apprentice

ASP.NET core objects are created for each request


After the application domain has been created and the HostingEnvironment object instantiated, ASP.NET creates and initializes core objects such as HttpContext, HttpRequest, and HttpResponse. The HttpContext class contains objects that are specific to the current application request, such as the HttpRequest and HttpResponse objects. The HttpRequest object contains information about the current request, including cookies and browser information. The HttpResponse object contains the response that is sent to the client, including all rendered output and cookies.

An HttpApplication object is assigned to the request


Defines the methods, properties, and events that are common to all application objects within an ASP.NET application. The request is processed by the HttpApplication pipeline.

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

.Net Apprentice

Application Events Life Cycle Events and the Global.asax file


During the application life cycle, the application raises events that you can handle and calls particular methods that you can override. To handle application events or methods, you can create a file named Global.asax in the root directory of your application. The Application_Start and Application_End methods are special methods that do not represent HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.

Global.asax S um ficheiro Global.asax por aplicao Web Colocado na raiz da directoria virtual Utilizado para tratar os eventos dos objectos Application e Session

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

.Net Apprentice

Application Events
Application_Start
Called when the first resource (such as a page) in an ASP.NET application is requested. The Application_Start method is called only one time during the life cycle of an application. You can use this method to perform startup tasks such as loading data into the cache and initializing static values.

Application_End
Called once per lifetime of the application before the application is unloaded.

Application_BeginRequest
Occurs as the first event in the HTTP pipeline chain of execution when ASP.NET responds to a request.

Application_EndRequest
Occurs as the last event to in the HTTP pipeline chain of execution when ASP.NET responds to a request.

Global.asax
<%@ Application Language="C#" %> <script runat="server"> void Application_Start(object sender, EventArgs e) // Code that runs on application startup } void Application_End(object sender, EventArgs e) // Code that runs on application shutdown } { {

void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs }

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

.Net Apprentice

Global.asax
void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started } void Session_End(object sender, EventArgs e) // Code that runs when a session ends. {

// Note: The Session_End event is raised only when the //sessionstate mode is set to InProc in the Web.config file. If //session mode is set to StateServer // or SQLServer, the event is not raised. } </script>

Application Application State


The HttpApplicationState class exposes two state collections: Contents and StaticObjects. Contents collection exposes all variable items that have been added to the application-state collection directly through code. The StaticObjects collection contains all of the objects created by using the <OBJECT> tags within the scope of the Application object. Application property of the Page object.

Set
Application.Contents[numusers]=0; // or Application[numUsers]=0; Application["AppStartTime"] = DateTime.Now;

Get
int n=int.Parse(Application["numusers"].ToString());

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

.Net Apprentice

Application Application methods, Lock and Unlock


allow only one thread at a time to access application-state variables.
void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started Application.Lock(); int n=int.Parse(Application["numusers"].ToString()); n++; Application.Contents["numusers"] = n; Application.UnLock(); }

Gesto de Estado no Servidor


O objecto Application permite armazenar informao para todos os utilizadores da aplicao web O uso de Session est condicionado sesso do browser cliente A sesso ASP.NET identificada pela propriedade SessionID do objecto session

Servidor Web Cliente Variveis de Sesso e de Aplicao SessionID


13

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

.Net Apprentice

Gesto de Estado no Cliente


Utilizao de cookies (persistentes / temporrias) Menos fivel que a gesto no servidor
O utilizador pode apagar as cookies

Limite ao tamanho da informao


Restries no cliente ao tamanho de ficheiros

Servidor Cliente

Cookies
14

Global.asax Session State


ASP.NET provides the cross-request state information (shopping carts, data scrolling, and so on) infrastructure that Web applications require, with built-in session-state functionality that enables you to take the following actions: Automatically identify and classify requests coming from a single browser client into a logical application session on the server. Store session-scoped data on the server for use across multiple browser requests. Raise appropriate session-lifetime management events (Session_OnStart, Session_OnEnd, and so on) that can be handled in application code. Automatically release session data if the browser does not revisit an application within a specified time-out period.
15

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

.Net Apprentice

Session
Identifying a Session
Each active ASP.NET session is identified and tracked using a 120-bit SessionID string containing only the ASCII characters that are allowed in URLs. SessionID values are generated using an algorithm that guarantees uniqueness so that sessions do not collide, and randomness so that a malicious user cannot use a new SessionID to calculate the SessionID of an existing session.

The SessionID strings are communicated across client-server requests either by means of an HTTP cookie or a modified URL with the SessionID string embedded, depending on how you configure the application settings. (sessionState cookieless="true)

Session
The SessionState class exposes two state collections: Contents and StaticObjects. The Contents collection exposes all variable items that have been added to the session-state collection directly through code. Session["AppStartTime"] = DateTime.Now; Session[Username]=varuserName; Session Timeout
Specifies the number of minutes that a session can remain idle before the server terminates it automatically. The default is 10 minutes. <sessionState timeout="1" /> // (in web.config file) Session.TimeOut=1

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

.Net Apprentice

Session Session Abandon


The Abandon method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out.

Session.Abandon();

Session Utilizao de vriaveis de Sesso e Aplicao


Contar nmeros de utilizadores na aplicao
(cdigo no Global.asax)
void Application_Start(object sender, EventArgs e) { // Code that runs on application startup Application["numusers"] = 0; } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started int n=int.Parse(Application["numusers"].ToString()); n++; Application["numusers"] = n; }

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

10

.Net Apprentice

Cookies ASP.NET Cookies


A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site. When a browser makes a request to the server, it sends the cookies for that server along with the request. When creating a cookie, you specify a Name and Value.

Cookies
Writing Cookies
Cookies are sent to the browser via the HttpResponse object that exposes a collection called Cookies. You can access the HttpResponse object as the Response property of your Page class
Response.Cookies["userName"].Value = "patrick"; Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1); // or HttpCookie aCookie = new HttpCookie("lastVisit"); aCookie.Value = DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(aCookie);

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

11

.Net Apprentice

Cookies
Reading Cookies you can read the cookies using the HttpRequest object, which is available as the Request property of your Page class.
if(Request.Cookies["userName"] != null) Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value); // or HttpCookie aCookie = Request.Cookies["userName"]; Label1.Text = Server.HtmlEncode(aCookie.Value); }

Tipos de Gesto de Estado

No Servidor
Objecto Application Informao fica disponvel para todos os utilizadores da aplicao Objecto Session S o utilizador da sesso ter acesso informao

No Cliente
Cookies Ficheiro de texto com informao do estado Propriedade ViewState, Control State Permite guardar valores entre pedidos pgina

Base de Dados Poder ser utilizada uma BD para manter informao do estado

Query strings Informao inserida no final da URL

23

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

12

.Net Apprentice

Autenticao ASP.NET
A autenticao o processo que verifica a identidade de um utilizador. A autorizao verifica se esse utilizador possui permisso para executar determinadas operaes. Em Asp.net existem trs tipos de autenticao:
Windows
Assenta no SO e no IIS Utilizador faz um pedido seguro que transferido ao IIS Aps as credencias serem verificadas, o acesso permitido. Mtodo usado por omisso Normalmente usado em Intranets

//no web.config <authentication mode="Windows" />

24

Autenticao
Forms
feito um acesso no autenticado a um Form HTML onde sero fornecidas as credenciais Aps verificao atribuda uma cookie de autenticao //no web.config <authentication mode="Windows" />

Microsoft Passport
Servio da Microsoft de autenticao centralizado Permite validao em vrios sites.- single login XML Web Service

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

13

.Net Apprentice

Autenticao
Forms authentication
Criao de um ticket para autenticao do utilizador num site O processamento realizado pelo mdulo
FormsAuthenticationModule

Passos de autenticao: Quando o utilizador pede uma pgina, se no est autenticado, redireccionado para uma pgina de autenticao. A pgina pede as credenciais do utilizador, normalmente nome e password. As credenciais so passados ao servidor que faz a validao, normalmente, numa base de dados Se a autenticao validada o utilizador redireccionado para a pgina que tinha pedido

Autenticao com Forms


Configurar o IIS para anonymous access Definida declarativamente no ficheiro web.config
Mode=forms loginUrl=login.aspx pgina de autenticao
<authentication mode=Forms> <forms loginUrl=login.aspx protection="All" timeout="30" name=".ASPXAUTH" path="/ requireSSL=false defaultUrl="default.aspx > </authentication>

Negar autorizao a todos (?) utilizadores no autenticados


<authorization> <deny users=? /> </authorization>

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

14

.Net Apprentice

Autenticao
Sequncia de eventos na autenticao

[Explained: Forms Authentication in ASP.NET 2.0]


http://msdn2.microsoft.com/en-us/library/Aa480476.aspx#pagexplained0002_objectives

Autenticao
Exemplo de cdigo na pgina login.aspx
protected void logon_Click(object sender, EventArgs e) { bool autenticado = false; string user = txtName.Text; string pass = txtpass.Text; // validao do utilizador na base de dados autenticado = myDAL.ValidateUser(user,pass); if (autenticado) FormsAuthentication.RedirectFromLoginPage(user, false); else lblMsg.Text = "Dados Invlidos"; }

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

15

.Net Apprentice

Comparao entre os Mtodos de Autenticao

Mtodo

Vantagens
Utiliza infra-estrutura Windows Controla acesso a informao sensvel Adequado maioria das aplicaes web Suporta todos os tipos de clientes Uma s assinatura para diversos sites web No necessita de armazenar informao do utilizador

Desvantagens
No se adequa maioria das aplicaes web

Windows

Forms

Baseia-se em cookies

Microsoft Passport

Baseia-se em cookies Servio pago

30

(C) Laboratrio .NET do Departamento de Engenharia Informtica do ISEP/IPP

16

Вам также может понравиться