Cookies ASP.NET通用提供程序-Roleprovider不会在cookie中缓存角色

Cookies ASP.NET通用提供程序-Roleprovider不会在cookie中缓存角色,cookies,roles,membership,roleprovider,Cookies,Roles,Membership,Roleprovider,具有讽刺意味的是,我的角色提供程序不再将角色缓存在cookie中。这在早些时候起了作用。不幸的是,我现在才注意到这一点,所以我无法说出问题的原因。但我认为这与UniversalProviders的新版本1.2(8月16日发布)的更新有关 我的roleprovider配置如下所示: <roleManager enabled="true" cacheRolesInCookie="true" cookieName="X_Roles" cookiePath="/" cookieProtecti

具有讽刺意味的是,我的角色提供程序不再将角色缓存在cookie中。这在早些时候起了作用。不幸的是,我现在才注意到这一点,所以我无法说出问题的原因。但我认为这与UniversalProviders的新版本1.2(8月16日发布)的更新有关

我的roleprovider配置如下所示:

 <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、带有sitemaptrimming的菜单等)一切都很好,但它只是不再缓存角色。会员资格提供者、会话状态等也工作正常,cookie设置正确

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

角色cookie设置得更早,但不再设置。我希望任何人都能帮助我解决我的问题

提前谢谢

致以最良好的祝愿

赫曼纽

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

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

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

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
    }
}
<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>
使用系统;
使用System.Collections.Generic;
使用System.Collections.Specialized;
使用系统配置;
使用系统数据;
使用System.Data.SqlClient;
使用System.Linq;
使用System.Web;
使用System.Web.Caching;
使用System.Web.Security;
命名空间MyProject.Providers
{
公共类CustomRoleProvider:RoleProvider
{
#区域属性
私有静态只读对象LockObject=新对象();
private int_cachetimeoutingminutes=0;
#端区
#RoleProvider的区域覆盖
公共覆盖无效初始化(字符串名称,NameValueCollection配置)
{
//设置属性
ApplicationName=config[“ApplicationName”];
_cachetimeoutingminutes=Convert.ToInt32(配置[“cachetimeoutingminutes”]);
//调用基方法
初始化(名称、配置);
}
/// 
///获取一个值,该值指示指定用户是否处于已配置applicationName的指定角色中。
/// 
/// 
///如果指定用户处于配置的applicationName的指定角色中,则为true;否则为false。
/// 
///要搜索的用户名。要搜索的角色。
public override bool IsUserInRole(字符串用户名、字符串角色名)
{
//获得角色
var userRoles=GetRolesForUser(用户名);
//如果存在,则返回
返回userRoles.Contains(roleName);
}
/// 
///获取指定用户在配置的applicationName中所处角色的列表。
/// 
/// 
///一个字符串数组,其中包含指定用户在配置的applicationName中的所有角色的名称。
/// 
///要为其返回角色列表的用户。
公共重写字符串[]GetRolesForUser(字符串用户名)
{
//如果用户未经过身份验证,则返回
如果(!HttpContext.Current.User.Identity.IsAuthenticated)返回null;
//如果缓存中存在,则返回
var cacheKey=string.format(“UserRoles_{0}”,username);
if(HttpRuntime.Cache[cacheKey]!=null)返回(字符串[])HttpRuntime.Cache[cacheKey];
//瓦尔斯
var userRoles=new List();
var sqlParams=新列表
{
新的SqlParameter(“@ApplicationName”,ApplicationName),
新的SqlParameter(“@UserName”,UserName)
};
锁定(锁定对象)
{
//运行存储过程>
使用(IDataReader博士)=
BaseDatabase.ExecuteDataReader(“aspnet\u UsersInRoles\u GetRolesForUser”,sqlParams.ToArray(),
常量(DatabaseConnectionName)作为SqlDataReader)
{
while(dr.Read())
{
添加(dr[“RoleName”].ToString());
}
}
}
//存储在缓存中,并在设置的分钟后过期
HttpRuntime.Cache.Insert(cacheKey,userRoles.ToArray(),null,
DateTime.Now.AddMinutes(\u cachetimeoutminutes),Cache.NoSlidingExpiration);
//返回
返回userRoles.ToArray();
}
/// 
///获取或设置要为其存储和检索角色信息的应用程序的名称。
/// 
/// 
///用于存储和检索角色信息的应用程序的名称。
/// 
公共重写密封字符串ApplicationName{get;set;}
//我跳过了其他方法,因为它们不适用于此场景
#端区
}
}
==================我的代码隐藏文件结束===============

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
    }
}
<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>
================我的Web.Config文件=======================

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
    }
}
<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>

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

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
    }
}
<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分钟自动过期一次。您可以根据自己的需要进行修改


干杯。

我也遇到了同样的问题,但我找到了一篇MS KB文章,似乎已经解决了这个问题。我安装了补丁,cookie再次出现

请参阅部分:ASP.Net第4期


希望这能帮助别人

我也有同样的问题。我很想用HttpRuntime.Cache实现我自己的缓存。感谢Kwex的提示-现在我知道我并不孤单,这肯定是库的问题,而不是项目中的其他地方。你能说说你是怎么想的吗