西皮流水DOTNET学习Blog

这是我的学习记录,欢迎您点评!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Time Tracker分析三(用户角色部分2--网站配置)

Posted on 2005-07-31 10:40  西皮流水  阅读(290)  评论(0编辑  收藏  举报

一。Web.config中的数据库连接字符串
        Web.config
<configuration>下面添加这行代码

<appSettings>
    <
addkey="ConnectionString" value="server=.;database=TimeTracker;uid=sa;pwd=;"/>
</appSettings>


二。Web.config 中From验证
 1. 将身份验证模式设置为 Forms<authentication mode="Forms"> 
 2. 设置 Forms 身份验证属性。 
        <forms
   a) loginUrl属性设置为DesktopDefault.aspx。如果ASP.NET没有找到针对初始请求的 Cookie,则
      DesktopDefault.aspx是用于重定向的 URL 
       
loginUrl = "DesktopDefault.aspx"
   b) 设置 Cookie 的名称。 
       
name = ".ASPXAUTH"/>
   
</authentication>
 3. 拒绝未经身份验证的用户访问此目录。 
        <authorization>
            <deny users="?"/> 
        </authorization>
    </system.web>
 </configuration>
 Web.config中的相关部分为:
<authentication mode="Forms">
    <forms name=".ASPXAUTH" protection="All" timeout="60" loginUrl="desktopdefault.aspx" />
</authentication>
<authorization>
    <deny users="?" />
</authorization>


三。调用Global.asax.cs类中的Application_BeginRequest方法
        Time Tracker启动时会首先调用Global.asax.cs类中的方法初始化一些重要的变量Application_BeginRequest事件在应用程序每次被请求执行时发生,该事件由Global.asax.cs类中的Application_BeginRequest方法响应处理。在Time Tracke中该方法根据浏览器的语言来设定服务线程所用的语言。代码如下:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    try
    {
        if (Request.UserLanguages != null)
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]);
        else
        // Default to English if there are no user languages
        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");

        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
    }
    catch (Exception ex)
    {
        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");
    }

}

为捕捉在执行期间发生的各种异常,这里采用了try-catch异常处理语句。
=
跟踪查看浏览器的语言信息。
?Request.UserLanguages
{Length=1}
    
[0]: "zh-cn" 当前浏览器使用中文
所以Request.UserLanguages[0] = "zh-cn"
= CultureInfoSystem.Globalization 的成员,表示有关特定区域性的信息,包括区域性的名称、书写体系和使用的日历,以及有关对常用操作(如格式化日期和排序字符串)提供信息的区域性特定对象的访问。CultureInfo.CreateSpecificCulture(Request.UserLanguages[0])创建与中文关联的特定区域性的文化信息。在命令窗口中查看,结果如下:

? Thread.CurrentThread.CurrentCulture{System.Globalization.CultureInfo}
    System.Object: {System.Globalization.CultureInfo}
    Calendar: {System.Globalization.GregorianCalendar}
    calendar: {System.Globalization.GregorianCalendar}
    compareInfo: {System.Globalization.CompareInfo}
    CompareInfo: {System.Globalization.CompareInfo}
    cultureID: 2052
    CurrentCulture: {System.Globalization.CultureInfo}
    CurrentUICulture: {System.Globalization.CultureInfo}
    DateTimeFormat: {System.Globalization.DateTimeFormatInfo}
    dateTimeInfo: {System.Globalization.DateTimeFormatInfo}
    DisplayName: "中文(中华人民共和国)"
    EnglishName: "Chinese (People's Republic of China)"
    groupSeparator: {Length=1}
    InstalledUICulture: {System.Globalization.CultureInfo}
    INTERNATIONAL_SPANISH_CULTURE: 3082
    InvariantCulture: {System.Globalization.CultureInfo}
    InvariantCultureID: 127
    IsNeutralCulture: false
    IsReadOnly: true
    LCID: 2052
    m_dataItem: 23
    m_InstalledUICultureInfo: {System.Globalization.CultureInfo}
    m_InvariantCultureInfo: {System.Globalization.CultureInfo}
    m_isReadOnly: true
    m_name: "zh-CN"
    m_userDefaultCulture: {System.Globalization.CultureInfo}
    m_userDefaultUICulture: {System.Globalization.CultureInfo}
    m_useUserOverride: true
    Name: "zh-CN"
    NativeName: "中文(简体) (中华人民共和国)"
    NEUTRAL_SPANISH_CULTURE: 10
    NumberFormat: {System.Globalization.NumberFormatInfo}
    numInfo: {System.Globalization.NumberFormatInfo}
    OptionalCalendars: {Length=1}
    Parent: {System.Globalization.CultureInfo}
    SPANISH_INTERNATIONAL_SORT: 3082
    SPANISH_TRADITIONAL_SORT: 1034
    TextInfo: {System.Globalization.TextInfo}
    textInfo: {System.Globalization.TextInfo}
    ThreeLetterISOLanguageName: "zho"
    ThreeLetterWindowsLanguageName: "CHS"
    TwoLetterISOLanguageName: "zh"
    UserDefaultCulture: {System.Globalization.CultureInfo}
    UserDefaultUICulture: {System.Globalization.CultureInfo}
    UseUserOverride: true
    zh_CHT_CultureID: 31748

= ThreadSystem.Threading的成员,创建并控制线程,设置其优先级并获取其状态。CurrentThread属性获取当前正在运行的线程。CurrentCulture属性获取或设置当前线程的区域性。
= CurrentUICulture属性获取或设置资源管理器使用的当前区域性以便在运行时查找区域性特定的资源。
= 如果没有用户语言或出现异常,将英语作为默认语言。
 
四。 调用Application_AuthenticateRequest方法
   调用Global.asax.cs类中的Application_AuthenticateRequest方法进行安全验证。Application_AuthenticateRequest事件在应用程序每次被请求执行时发生,该事件由Global.asax.cs类中的Application_AuthenticateRequest方法响应处理
   
首先声明一个字符串变量userInformation,并赋初值为空。接下来测试该应用程序是否通过验证,在首次时其结果一定是false,所以程序会跳过if语句中的代码。相关代码:
string userInformation = String.Empty;
if (Request.IsAuthenticated == true)

这个里面有个BUG(前面说过),详细代码如下:

//  当安全模块已建立用户标识时发生。
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    string userInformation = String.Empty;
    // 这里有个Bug,先不管他
    if (Request.IsAuthenticated == true) 
    {
       // Create the roles cookie if it doesn't exist yet for this session.
       if ((Request.Cookies[UserRoles] == null) || (Request.Cookies[UserRoles].Value == "")) 
       {
            // Retrieve the user's role and ID information and add it to
            // the cookie
            TTUser user = new TTUser(User.Identity.Name);
            if (!user.Load())
            {
            // The user was not found in the Time Tracker database so add them using
            // the default role.  Specifying a UserID of 0 will result in the user being
 
            // inserted into the database.
            TTUser newUser = new TTUser(0, 
                                 Context.User.Identity.Name,
                                 String.Empty, 
                                 ConfigurationSettings.AppSettings[CfgKeyDefaultRole]);
             newUser.Save();
             user = newUser;
          }
                
        // Create a string to persist the role and user id
        userInformation = user.UserID + ";" + user.Role + ";" + user.Name;

        // Create a cookie authentication ticket.
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1,                              // version
                        User.Identity.Name,       // user name
                        DateTime.Now,                   // issue time
                        DateTime.Now.AddHours(1),       // expires every hour
                        false,                          // don't persist cookie
                        userInformation                   
                        );

        // Encrypt the ticket
        String cookieStr = FormsAuthentication.Encrypt(ticket);

        // Send the cookie to the client
        Response.Cookies[UserRoles].Value = cookieStr;
        Response.Cookies[UserRoles].Path = "/";
        Response.Cookies[UserRoles].Expires = DateTime.Now.AddMinutes(1);

        // Add our own custom principal to the request containing the user's identity, the user id, and
        // the user's role 
        Context.User = new CustomPrincipal(User.Identity, user.UserID, user.Role, user.Name);
         }
         else 
         {
             // Get roles from roles cookie
             FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[UserRoles].Value);
             userInformation = ticket.UserData;

             // Add our own custom principal to the request containing the user's identity, the user id, and
             // the user's role from the auth ticket
             string [] info = userInformation.Split( new char[] {';'} );
             Context.User = new CustomPrincipal(
                        User.Identity,
                        Convert.ToInt32(info[0].ToString()),
                        info[1].ToString(),
                        info[2].ToString());
           }
      }
  }


五  Global.asax.cs中返回站点根路径(GetApplicationPath(HttpRequest request))

        public static string GetApplicationPath(HttpRequest request)
        {
            string path = string.Empty;
            try
            {
                if(request.ApplicationPath != "/")
                    path = request.ApplicationPath;
            }
            catch (Exception e)
            {
                throw e;
            }

            return path;
        }