AuthenticationService.CreatingCookie 事件

定义

当设置身份验证 Cookie 时发生。

public:
 static event EventHandler<System::Web::ApplicationServices::CreatingCookieEventArgs ^> ^ CreatingCookie;
public static event EventHandler<System.Web.ApplicationServices.CreatingCookieEventArgs> CreatingCookie;
member this.CreatingCookie : EventHandler<System.Web.ApplicationServices.CreatingCookieEventArgs> 
Public Shared Custom Event CreatingCookie As EventHandler(Of CreatingCookieEventArgs) 

事件类型

示例

以下示例演示如何将事件处理程序 CreatingCookie 绑定到 Global.asax 文件的 方法中的 Application_Start 事件。

void Application_Start(object sender, EventArgs e)
{
    System.Web.ApplicationServices.AuthenticationService.CreatingCookie 
        += new EventHandler<System.Web.ApplicationServices.CreatingCookieEventArgs>
        (AuthenticationService_CreatingCookie);
}
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    AddHandler System.Web.ApplicationServices.AuthenticationService.CreatingCookie, _
        AddressOf Me.AuthenticationService_CreatingCookie
End Sub

以下示例演示 Global.asax 文件中 事件的事件处理程序 CreatingCookie 。 事件处理程序通过将 属性中的 CustomCredential 值添加到 UserData 属性来自定义身份验证 Cookie。 CustomCredential仅当知道 属性中的数据不敏感时,才将 属性存储在 Cookie 中。 恶意用户可以访问 Cookie 中的值。

void AuthenticationService_CreatingCookie(object sender, 
    System.Web.ApplicationServices.CreatingCookieEventArgs e)
{
    FormsAuthenticationTicket ticket = new
          FormsAuthenticationTicket
            (1,
             e.UserName,
             DateTime.Now,
             DateTime.Now.AddMinutes(30),
             e.IsPersistent,
             e.CustomCredential,
             FormsAuthentication.FormsCookiePath);

    string encryptedTicket =
         FormsAuthentication.Encrypt(ticket);

    HttpCookie cookie = new HttpCookie
         (FormsAuthentication.FormsCookieName,
          encryptedTicket);
    cookie.Expires = DateTime.Now.AddMinutes(30);

    HttpContext.Current.Response.Cookies.Add(cookie);
    e.CookieIsSet = true;
}
Sub AuthenticationService_CreatingCookie(ByVal sender As Object, _
                 ByVal e As System.Web.ApplicationServices.CreatingCookieEventArgs)
    Dim ticket As FormsAuthenticationTicket = New _
       FormsAuthenticationTicket _
        (1, _
         e.Username, _
         DateTime.Now, _
         DateTime.Now.AddMinutes(30), _
         e.IsPersistent, _
         e.CustomCredential, _
         FormsAuthentication.FormsCookiePath)
        
    Dim encryptedTicket As String = FormsAuthentication.Encrypt(ticket)
    
    Dim cookie As HttpCookie = New _
        HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
    cookie.Expires = DateTime.Now.AddMinutes(30)
    
    HttpContext.Current.Response.Cookies.Add(cookie)
    e.CookieIsSet = True
End Sub

注解

验证 CreatingCookie 用户凭据后设置身份验证 Cookie 时,将引发 事件。 为 事件创建事件处理程序以 CreatingCookie 自定义身份验证 Cookie。

适用于

另请参阅