首先在 web.config 中添加这个(system.web)
<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>
然后将此行添加到 Application_Start 中的 Global.asax
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"UserProfile", "UserId", "UserName", autoCreateTables: true);
然后您可以将用户添加到这样的角色
var roles = (SimpleRoleProvider)Roles.Provider;
roles.AddUsersToRoles(new[] { "username1", "username2", ... },
new[] { "role1", "role2", .... });
然后在控制器或方法上,您可以添加 AuthorizeAttribute 如下所示
[Authorize(Roles="role1,role2,...")]