Академический Документы
Профессиональный Документы
Культура Документы
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
Web Server
Web Server
.Net Apprentice
.Net Apprentice
.Net Apprentice
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
.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 }
.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>
Set
Application.Contents[numusers]=0; // or Application[numUsers]=0; Application["AppStartTime"] = DateTime.Now;
Get
int n=int.Parse(Application["numusers"].ToString());
.Net Apprentice
.Net Apprentice
Servidor Cliente
Cookies
14
.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
.Net Apprentice
Session.Abandon();
10
.Net Apprentice
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);
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); }
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
23
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
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
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
14
.Net Apprentice
Autenticao
Sequncia de eventos na autenticao
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"; }
15
.Net Apprentice
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
30
16