现在的位置: 首页 > 综合 > 正文

转web.config文件配置详解

2012年10月31日 ⁄ 综合 ⁄ 共 7944字 ⁄ 字号 评论关闭

1、连接数据库字符串的定义节

<connectionStrings>

    <remove name="LocalSqlServer" /> <!--remove是指删除系统中自带的Web.config(位于C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG)中的LocalSqlServer配置,以便使用如下的LocalSqlServer-->

    <add name="stuclubSqlServer" connectionString="server=(local);uid=;pwd=;Trusted_Connection=yes;database=" /><!--用于连接数据库,其中的用户名密码已略去~-->

    <add name="storageSqlServer" connectionString="server=(local);uid=;pwd=;Trusted_Connection=yes;database=" />

    <add name="LocalSqlServer" connectionString="server=(local);uid=;pwd=;Trusted_Connection=yes;database=" />

</connectionStrings>

程序中如何使用这个配置呢? 代码如下: 

stringconnstr=ConfigurationManager.ConnectionStrings

["stuclubSqlServer"].ToString(); //这就得到了connectionString的值:

server=(local);uid=;pwd=;Trusted_Connection=yes;database=stuclub20 

SqlConnection conn = new SqlConnection(connstr); //建立连接 

conn.Open();//打开连接  


2、基于Forms的验证模块

使用的配置节如下:

<authentication mode="Forms">

      <forms name=".ASPXAUTH" loginUrl="~/user/login.aspx"

             defaultUrl="default.aspx" protection="All"

             timeout="60" path="/" requireSSL="false"

             slidingExpiration="true" cookieless="UseDeviceProfile"

              domain ="stuclub.cn" enableCrossAppRedirects="false">

        <credentials passwordFormat="SHA1"/>

      </forms>

      <passport redirectUrl="internal"/>

    </authentication>

    <anonymousIdentification enabled="true" cookieName=".ASPXANONYMOUS" cookieTimeout="100000" cookiePath="/" cookieRequireSSL="false" cookieSlidingExpiration="true" cookieProtection="None" domain=""/>

说明:<authentication>节中,mode="Forms" 表示我们使用的验证方式是基于Forms的验证, 当然还包括基于Windows的和Passport的验证方式.

<forms></forms>配制节最为关键, 其中的name指Cookie的名字,timeout指Cookie的过期时间,domain指使用的域名,我们网站就将此设置为stuclub.cn, 这样可以保证Cookie跨域访问,即可以实现多个子网共享用户的状态。其他的属性大家百度上一搜就会明白,在此我不多说。我要说明的是,这些配置在代码中是如何读取和实现的。

Forms节中的配置主要供Asp.net2.0自带的身份验证基制使用的,用于登录验证模块:

在登录验证事件触发后,我们要执行以下操作:             string username = txtUserName.Text;

            string password = txtPwd.Text;

            User userToLogin = null;

            LoginUserStatus loginStatus = UserManager.ValidateUser(username, password, out userToLogin);//验证用户是否是合法用户,即从数据库中读取用户的注册信息,进行比较,如果一致,则成功!                                                                                                          //进行验证要用到下面的成员资格(Membership)模块,下面会说明 if (loginStatus == LoginUserStatus.Success) //如果验证成功

            {

                FormsAuthentication.SetAuthCookie(userToLogin.Username, true);//将身份验证Cookie添加到Http响应,供程序使用,这里的Cookie属性就是配置文件中设置的相关属性

            } 但是,如果我想自己写代码实现Cookie的相关属性控制,该怎么办呢?看看下面的代码先! //在OL中有如下的代码 if (loginStatus == LoginUserStatus.Success || (enableBannedUsersToLogin && loginStatus == LoginUserStatus.AccountBanned))

            {

                HttpCookie formsAuthCookie;

                formsAuthCookie = FormsAuthentication.GetAuthCookie(userToLogin.Username, autoLoginUser);                 UserCookie userCookie = context.User.GetUserCookie();//得到自定义的Cookie,用于获取上次访问时间,和身份验证无关,此Cookie的名字是"OL-UserCookie:" + user.UserId.ToString();                 userCookie.WriteCookie(formsAuthCookie, 30, autoLoginUser);//代替FormsAuthentication.SetAuthCookie方法,以实现自定义Cookie设置。

            } //下面是UserCookie类中的WriteCookie方法 public void WriteCookie(HttpCookie cookie, int days, bool autoLogin)

        {

            string cookieDomain = Globals.GetSiteSettings().CookieDomain;

            string currentURL = HttpContext.Current.Request.Url.AbsoluteUri;

            Regex matchNotTLD = new Regex("[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);             //Check if we are not breaking functionality because of bad domain setting

            if ((matchNotTLD.IsMatch(cookieDomain)) && (currentURL.IndexOf(cookieDomain) > -1))

            {

                cookie.Path = "/";

                cookie.Domain = cookieDomain;

            }             if (autoLogin)

                cookie.Expires = DateTime.Now.AddDays(days);//设置过期时间             context.Response.Cookies.Add(cookie);

        }

大家需要注意的是,asp.net2.0里身份验证的机制对我们是隐藏的,我们只需进行以上的Forms节配置和以上代码的编写就可以完成身份验证了,至于具体的Cookie值是如何读取的,匿名用户是如何得到的及角色是如何管理的都在asp.net2.0内部实现了,这到底是如何实现的呢,下面我简要解释一下:

在machine.config文件(路径为C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG)中, 大家会看到如下的配置:

<section name="httpCookies" type="System.Web.Configuration.HttpCookiesSection, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

      <section name="anonymousIdentification" type="System.Web.Configuration.AnonymousIdentificationSection, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication" />

      <section name="roleManager" type="System.Web.Configuration.RoleManagerSection, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication" />

这就是用来处理Cookie的2.0自带的处理类,即System.Web.Configuration.HttpCookiesSection,当然还有其他的一些配置如:anonymousIdentification、roleManager,这两个是分别用来处理匿名用户和角色管理的。

如:第一次请求页面时,asp.net IIS处理程序会调用System.Web.Configuration.AnonymousIdentificationSection类,以获取匿名用户的相关信息,如匿名用户的用户名。

这些自带的类的实现对我们是隐藏的,大家可以不必去关心他。微软的想法就是把我们都变成傻瓜,呵呵。 当然我们可以自己通过写代码来实现,只是比较麻烦了,大家有兴趣可以找些相关的资料啦~~

然而,仅通过Forms这个配置节是不能够进行完整的身份验证的,它只是设置了用户身份验证需要的一些必要属性,如Cookie路径,Cookie域,超时时间等等,并没有说明如何进行用户验证,以及验证成功以后用户拥有哪些角色,用户能做些什么。只有结合Membership、roleManager和profile配置和相关处理机制才能进行完整的身份验证。 以下就来介绍这三个配置。

3、Membership配置节

   <membership   userIsOnlineTimeWindow="60">

      <providers>

        <clear />

        <add name="AspNetSqlMembershipProvider" applicationName="stuclub"

             type="Stuclub.Users.DataProviders.SqlMembershipProvider, Stuclub.CommonLib" connectionStringName="LocalSqlServer"

             enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="false"

             minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0"

             requiresUniqueEmail="true" passwordFormat="Clear" />

      </providers>

    </membership>

此节用于成员资格的验证,即验证用户的密码,Email,密码丢失管理,获取用户等等等。

其中的<providers>节配置了进行成员资格验证的提供者,这里的提供者是:Stuclub.Users.DataProviders.SqlMembershipProvider类,此类在 Stuclub.CommonLib   程序集中。

<clear/>用于清除系统自带的Machine.config中的配置。

<add>节中,applicationName指我们的应用程序的名称,asp.net2.0中设置此属性的目的是多个应用程序共用一个数据库用户表,这样可以很容易的扩展别的应用程序,而不用改动数据库表。type指进行成员资格验证的提供者(就是一个类)的类型信息。connectionStringName指定使用哪个数据库,这里是LocalSqlServer,请参见 1、连接数据库字符串的定义节。

注意:这里的提供者不是使用 asp.net2.0自带的提供者类,而是的重写System.Web.Security.MembershipProvider类的自定义类。

如下的roleManager和profile和Membership配置是一样的道理,不在赘述!

4、roleManager配置节

    <roleManager enabled="true" cacheRolesInCookie="true" cookieName=".StuRoles"

                 cookieTimeout="90" cookiePath="/" cookieRequireSSL="false" cookieSlidingExpiration="true" createPersistentCookie="true" cookieProtection="All" maxCachedResults="1000">

      <providers>

        <clear />

        <add

           connectionStringName="LocalSqlServer"

           applicationName="stuclub"

           name="AspNetSqlRoleProvider"

           type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

      </providers>

    </roleManager>

这里的提供者是asp.net2.0自带的,也可以自己重写。此类用来管理用户的角色,如获取、添加和删除用户的角色,以供程序使用。

如以下代码: ///<summary>///添加角色///</summary> ///<param name="roleName"></param> publicstaticvoidAddRole(stringroleName) { if(!System.Web.Security.Roles.Provider.RoleExists(roleName))//asp.net2.0自带的角色管理 System.Web.Security.Roles.Provider.CreateRole(roleName); } //判断数据库中是否存在该角色 publicstaticboolRoleExists(stringroleName) { returnSystem.Web.Security.Roles.Provider.RoleExists(roleName); }

5、profile配置节

    <profile enabled="true">

      <providers>

        <clear />

        <add name="SqlProvider"

             type="System.Web.Profile.SqlProfileProvider"

             connectionStringName="LocalSqlServer"

             applicationName="stuclub"

             description="SqlProfileProvider for SampleApplication" />

      </providers>

    </profile>

这里的提供者是asp.net2.0自带的,也可以自己重写。

6、<pages>节

    <pages validateRequest="false" enableEventValidation="false" autoEventWireup="true">

      <namespaces>

        <add namespace="System.Globalization"/>

             </namespaces>

      <controls>

            </controls>

    </pages>

此节用于配置使用的命名空间和自定义控件的前缀,不再多说

7、HttpModules节

   <httpModules>

      <add name="stuHttpModule" type="Stuclub.HttpModule.BaseHttpModule, Stuclub.CommonLib"/>

抱歉!评论已关闭.