If you have already wired Authentication and Membership using SQL Server in your site it will be easy for you. Just follow these steps:
Create role store on sql server
aspnet_regsql -S .\SQLExpress -E -A r
-S specifies the server, which is (.\SQLExpress) in this example.
-E specifies to use Windows authentication to connect to SQL Server.
-A r specifies to add only the role provider feature.
Add connection string for role provider:
<connectionStrings>
<add name="MyLocalSQLServer"
connectionString="Initial Catalog=aspnetdb;
data source=.\sqlexpress;Integrated Security=SSPI;" />
</connectionStrings>
Add role manager:
<system.web>
<roleManager enabled="true" defaultProvider="MySqlRoleProvider" >
<providers>
<clear/>
<add name="MySqlRoleProvider" connectionStringName="MyLocalSQLServer"
applicationName="MyAppName"
type="System.Web.Security.SqlRoleProvider" />
</providers>
</roleManager>
</system.web>
Now you can use Role based stuff in your pages (supposing you have already enabled authentication [windows or forms])
Test ASPX:
All Defined Roles: <asp:Lable id="lblAllRoles" runat="server" /><br/>
Your Roles: <asp:label id="lblMyRoles" runat="server" /><br/>
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
//here we are supposing that user is already authenticated
StringBuilder sb=new StringBuilder();
//gets roles for currently authenticated user
var roles = Roles.GetRolesForUser();
foreach (var v in roles)
sb.Append(", " + v);
lblMyRoles.Text = sb.ToString();
sb.Remove(0,sb.Length);
string [] allRoles = Roles.GetAllRoles();
foreach(var v in allRoles)
sb.Append(", " + v);
lblAllRoles.Text = sb.ToString();
}
Simillarly you can use Role.IsUserInRole("ROLE_NAME")
to check if user is assigned particular role.
TheVillageIdiot
2009-09-06 17:45:18