[英]Unable to cast object of type 'System.Web.Security.SqlRoleProvider' to type 'WebMatrix.WebData.SimpleRoleProvider'
I developing an mvc web app with Entity Frame]work. 我开发了一个带有Entity Frame的mvc web应用程序。 I've enabled database migration so that i can add some seed data on each update. 我已启用数据库迁移,以便我可以在每次更新时添加一些种子数据。 More specifically, i want to add two users and two roles; 更具体地说,我想添加两个用户和两个角色; so the configuration file looks like this: 所以配置文件看起来像这样:
var roles = (SimpleRoleProvider)Roles.Provider;
var membership = (SimpleMembershipProvider)Membership.Provider;
//// create two roles
if (!roles.RoleExists("Admin"))
{
roles.CreateRole("Admin");
}
if (!roles.RoleExists("User"))
{
roles.CreateRole("User");
}
However there seems to be a problem during the casting; 但是在铸造期间似乎存在问题; it throws an exception 它引发了一个例外
Unable to cast object of type 'System.Web.Security.SqlRoleProvider' to type 'WebMatrix.WebData.SimpleRoleProvider'.
I suspect that this might be a configuration issue, but i'm not really sure. 我怀疑这可能是配置问题,但我不确定。 Does anyone stumbled across the same problem? 有没有人偶然发现同样的问题?
That's because SqlRoleProvider
does not inherit SimpleRoleProvider
. 那是因为SqlRoleProvider
不继承SimpleRoleProvider
。 However, you can try using SimpleRoleProvider
Constructor ( RoleProvider
) : 但是,您可以尝试使用SimpleRoleProvider
构造函数( RoleProvider
) :
var roles = new SimpleRoleProvider(Roles.Provider);
I sorted this out. 我整理了这个。 The problem apparently was related to web configuration. 问题显然与网络配置有关。 I added the following lines to the web.config file: 我在web.config文件中添加了以下行:
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
to explicitly set the role provider. 显式设置角色提供程序。 So now the Roles.Provider
returns an instance of WebMatrix.WebData.SimpleRoleProvider; 所以现在Roles.Provider
返回一个WebMatrix.WebData.SimpleRoleProvider实例; thus i don't need to cast any more 因此我不需要再施展
I solved this by placing below code in web.config between 我通过在web.config之间放置代码来解决这个问题
<roleManager enabled="true" defaultProvider="simple">
<providers>
<clear />
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="simple">
<providers>
<clear />
<add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.