简体   繁体   中英

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. 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 . However, you can try using SimpleRoleProvider Constructor ( 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:

<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; thus i don't need to cast any more

I solved this by placing below code in web.config between

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM