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。

適用於

另請參閱