首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ASP.NET通用提供程序- Roleprovider不缓存cookie中的角色

ASP.NET通用提供程序- Roleprovider不缓存cookie中的角色
EN

Stack Overflow用户
提问于 2012-09-04 07:55:03
回答 2查看 2.5K关注 0票数 3

具有讽刺意味的是,我的角色提供程序不再将角色缓存在cookie中。刚才起作用了。不幸的是,我现在才注意到这一点,所以我不能说是什么原因造成了这个问题。但我认为这与更新新版本1.2版的通用供应商有关(8月16日发布)。

角色提供程序的配置如下所示:

代码语言:javascript
复制
 <roleManager enabled="true" cacheRolesInCookie="true" cookieName="X_Roles" 
cookiePath="/" cookieProtection="All" cookieRequireSSL="true" cookieSlidingExpiration="true" cookieTimeout="1440" 
createPersistentCookie="false" domain="" maxCachedResults="25" defaultProvider="XManager_RoleProvider">
<providers>
<clear/>
<add name="XManager_RoleProvider" type="ManagersX.XManager_RoleProvider, AssemblyX" 
connectionStringName="XEntities" applicationName="/" rolesTableName="Roles" roleMembershipsTableName="Users_Roles"/>
</providers>
</roleManager>

使用rolemanager (loginview、菜单和站点地图修剪等)一切都很好,但它只是不再缓存角色了。成员资格提供程序、会话状态等也运行良好,并且正确设置了它们的cookie。

静态角色类的所有属性都被正确设置,并且Httpcontext (IsSecureConnection等)中的所有内容都是正确设置的。也是正确的。

角色cookie是早些时候设置的,但现在不是了。我希望有人能帮我解决我的问题。

提前谢谢。

诚挚的问候,

HeManNew

更新:没有人有同样的问题或提示给我,好吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-09-19 13:43:14

下面是我编写的自定义角色提供程序的详细信息,它使用适当的缓存,并且不会在每次加载页面时命中数据库。

=============我的代码隐藏文件===============

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.Security;

namespace MyProject.Providers
{
    public class CustomRoleProvider : RoleProvider
    {
        #region Properties

        private static readonly object LockObject = new object();
        private int _cacheTimeoutInMinutes = 0;

        #endregion

        #region Overrides of RoleProvider

        public override void Initialize(string name, NameValueCollection config)
        {
            // Set Properties
            ApplicationName = config["applicationName"];
            _cacheTimeoutInMinutes = Convert.ToInt32(config["cacheTimeoutInMinutes"]);

            // Call base method
            base.Initialize(name, config);
        }

        /// <summary>
        /// Gets a value indicating whether the specified user is in the specified role for the configured applicationName.
        /// </summary>
        /// <returns>
        /// true if the specified user is in the specified role for the configured applicationName; otherwise, false.
        /// </returns>
        /// <param name="username">The user name to search for.</param><param name="roleName">The role to search in.</param>
        public override bool IsUserInRole(string username, string roleName)
        {
            // Get Roles
            var userRoles = GetRolesForUser(username);

            // Return if exists
            return userRoles.Contains(roleName);
        }

        /// <summary>
        /// Gets a list of the roles that a specified user is in for the configured applicationName.
        /// </summary>
        /// <returns>
        /// A string array containing the names of all the roles that the specified user is in for the configured applicationName.
        /// </returns>
        /// <param name="username">The user to return a list of roles for.</param>
        public override string[] GetRolesForUser(string username)
        {
            // Return if User is not authenticated
            if (!HttpContext.Current.User.Identity.IsAuthenticated) return null;

            // Return if present in Cache
            var cacheKey = string.format("UserRoles_{0}", username);
            if (HttpRuntime.Cache[cacheKey] != null) return (string[]) HttpRuntime.Cache[cacheKey];

            // Vars
            var userRoles = new List<string>();
            var sqlParams = new List<SqlParameter>
                                {
                                    new SqlParameter("@ApplicationName", ApplicationName),
                                    new SqlParameter("@UserName", username)
                                };

            lock (LockObject)
            {
                // Run Stored Proc << Replace this block with your own Database Call Methods >>
                using (IDataReader dr =
                    BaseDatabase.ExecuteDataReader("aspnet_UsersInRoles_GetRolesForUser", sqlParams.ToArray(),
                                                   Constants.DatabaseConnectionName) as SqlDataReader)
                {
                    while (dr.Read())
                    {
                        userRoles.Add(dr["RoleName"].ToString());
                    }
                }
            }

            // Store in Cache and expire after set minutes
            HttpRuntime.Cache.Insert(cacheKey, userRoles.ToArray(), null,
                                     DateTime.Now.AddMinutes(_cacheTimeoutInMinutes), Cache.NoSlidingExpiration);

            // Return
            return userRoles.ToArray();
        }

        /// <summary>
        /// Gets or sets the name of the application to store and retrieve role information for.
        /// </summary>
        /// <returns>
        /// The name of the application to store and retrieve role information for.
        /// </returns>
        public override sealed string ApplicationName { get; set; }

        // I skipped the other methods as they do not apply to this scenario

        #endregion
    }
}

代码隐藏文件的=============端===============

=============我的Web.Config文件=======================

代码语言:javascript
复制
<roleManager enabled="true" defaultProvider="CustomRoleManager">
  <providers>
    <clear />
    <add name="SqlRoleManager" type="System.Web.Security.SqlRoleProvider" connectionStringName="AspnetDbConnection" applicationName="MyApplication"/>
    <add name="CustomRoleManager" type="MyProject.Providers.CustomRoleProvider" connectionStringName="AspnetDbConnection" applicationName="MyApplication" cacheTimeoutInMinutes="30" />
  </providers>
</roleManager>

我的=============文件================的末尾

缓存设置为每隔30分钟自动过期。你可以在你认为合适的时候修改这个。

干杯。

票数 7
EN

Stack Overflow用户

发布于 2013-03-06 22:35:14

我也有同样的问题,但我找到了一篇MS的文章,似乎已经解决了它。我安装了补丁,饼干就重新出现了。

http://support.microsoft.com/kb/2750147

参见本节: ASP.Net第4期。

希望这能帮到别人!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12259052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档