Home » Asp.net

How to set roles to a particular user dynamically using asp.net membership???

Hi …

I have used asp.net membership and roles in my application. Its working fine.

I have an (.aspx page) where i have placed create user wizard, to create new user dynamically.

The same way i have created roles in my application.

What my requirement is, how to set roles dynamically to a particular user from my (aspx page).


2 Answers Found


Answer 1

Please read the section in this article:

<asp:createuserwizard> wizard  step 1: gathering user-account data


Answer 2

Hope the discussion on the same here would help you.

Have a look at this also.



I have created an asp.net website with SQL Server based form authentication and authorization. Now, we are moving this pure asp.net website to Sharepoint 2010 website. I have developed 5 webparts for my asp.net website to migrate to Sharepoint. All these webparts are avilable for access in the same page. Now I need to implement authentication and authorization for access to these webparts in Sharepoint. I am newbie to sharepoint. Can someone provide me how can I provide authorization and authentication in Sharepoint, which should use the current SQL Server based form authentication and authorization(roles and users of my existing asp.net website) and how can I map roles and users of my existing asp.net website to Sharepoint.

Please reply ASAP.

Thanks & Regards
Mahendra Babu


Hi …

I have used asp.net membership and roles in my application. Its working fine.

I have an (.aspx page) where i have placed create user wizard, to create new user dynamically.

The same way i have created roles in my application.

What my requirement is, how to set roles dynamically to a particular user from my (aspx page).



am switched from windows application to web application

i want full application  of Membership & role management (Dynamicaly create User, role,members .....)

if available please inform me or give me information how to create application steps


I am currently working in an ASP.Net application where i need to implement ASP.Net Membership and Roles. I have used Login controls in my pages. Also I am using a menu in the master page, which is getting data bindings from database. For data bindings I am using XMLDatasource and a transform file (.xslt file). I need to bind the data to the Menu based on the user roles.


My issue is that the generated Menu is not behaving consistently. Sometimes it will show the correct menu for a particular role and some times it will show previously loaded data.

Providing my code here:


private void LoadMenuItems() {

System.Security.Principal.IPrincipal User;

User = System.Web.HttpContext.Current.User; 

string appName = HttpContext.Current.Request.ApplicationPath;
string username = User.Identity.Name;

DataSet menuSet = new DataSet();  

xmlDataSource.Data = null;

menuSet = GetMenuDetails(appName, username);

menuSet.DataSetName = "Menus";

menuSet.Tables[0].TableName = "Menu"; 

DataRelation relation = new DataRelation("ParentChild",

relation.Nested = menuSet.Relations.Add(relation);

xmlDataSource.Data = menuSet.GetXml();

masterpage.master code:

<asp:Menu ID="Menu2" runat="server" Width="200px" DataSourceID="xmlDataSource">
                            <asp:MenuItemBinding DataMember="MenuItem" NavigateUrlField="NavigateUrl" TextField="Text"
                                ToolTipField="ToolTip" />
<asp:XmlDataSource ID="xmlDataSource" TransformFile="~/MenuFile.xslt" XPath="MenuItems/MenuItem"


Please help me in solving this issue.

Thank You.


1. In asp.net you can use sitemaps to allow a user, once authenticated, to see the areas/links of a web app they have access to.

2. You can also use loginview to set visibility of buttons that allow a user to be able to enter new, edit and/or print data.

For both examples above, how would you ideally incorporate such features into a multipage silverlight business app, are there silverlight specific methods to achieve the same???    Thanks 



         i wanna to create users and assign permissions dynamically...how can i do it...please guide me in a good way....as i am new to development....i go through many articles and applications but didnt get it...

thanks in advance....


I am evaluating ASP.NET Membership for an intranet Silverlight app.

I want users to be automatically authenticated for my application with their windows logon.
Thus I configured Windows Authentication.
I would like to store user settings like email-address in using the SqlMembershipProvider and not AD.

It seems that storing user settings using the SqlMembershipProvider is not supported with Windows Authentication.

Is this really so (using .NET 4)?

If so:

What is the rationale behind this?
IMHO authentication, user settings and authorization are distinct aspects.
User settings could easily be stored (identified by user name) using the SqlMembershipProvider with authentication and password management being supplied by Windows. What is the recommended solution for my scenario?

hi friends

i want to develope general code or module or structure of web application wich handle multiple user ,their role and right, and according to their rights and role menu will be display.so i can integreate it in any website.

kindly provide me solution for asp.net 3.5,C# working environment, and sqlserver 2005 environment.

what is the structure for database? i want only one database not asp.net database.

 can i make login control type assembly(dll)?how?

Thanking you


When assigning a 'user mapped Login' to a database and role membership to that database, is it redundent to check/enable db_datareader, db_datawriter as well as db_owner or will check/enable db_owner become all that is necessary to provide role membership to the database?

I'm currently in the process of testing some upgrades from SP2007 to SP2010, and one issue we are having is not being able to add permissions to FBA users from our Windows Auth version of our site.

I setup the Web Application to be Claims Based, the Default Zone authentication is setup to be Windows, and created an extended web application in the Internet Zone, to use FBA.  If I add the Role and Membership provider sections to the Central Admin site web.config, and add entries to the people picker section of the web.config I can find my FBA users on the central admin site.  When I go to the Windows Auth version of our site, I am unable to find any FBA users in the people picker. (I have added the Memberhsip and Role provider entries to the web.config of this site, as well as the PeoplePickerWildcards entries) If I go to the FBA version of the site I can find the FBA users.  

We do all the maintenance to the site in the Windows Auth version, and leave the FBA for external users only, so we'd like to be able to add permissions for FBA users in the Windows Auth site.  Anything I may be forgetting to make this work?



I've seen a few posts out there where they show how to filter by binding to text boxes, how do I filter by Binding to the User name from the User table in ASP.NET Membership provider.

I want to filter the Datasets so each user can only see data related to him.

How do I pass the Membership class to the 'decllarative domain'?

Thank you,



I'm building a website using VS2008 Pro, Win XP Pro, MySql 5.1 and Connector 6.3.5. My connection to the database seems to work fine when I attempt to pull data from tables to build pages but when I try to create users for the website using the create user wizard I get the followin error:

Access denied for user ''@'localhost' (using password: NO) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: MySql.Data.MySqlClient.MySqlException: Access denied for user ''@'localhost' (using password: NO)

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[MySqlException (0x80004005): Access denied for user ''@'localhost' (using password: NO)]
   MySql.Data.MySqlClient.MySqlStream.ReadPacket() +251
   MySql.Data.MySqlClient.NativeDriver.AuthenticateNew() +259
   MySql.Data.MySqlClient.NativeDriver.Authenticate() +79
   MySql.Data.MySqlClient.NativeDriver.Open() +2286
   MySql.Data.MySqlClient.Driver.Open() +70
   MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings) +160
   MySql.Data.MySqlClient.MySqlPool.CreateNewPooledConnection() +39
   MySql.Data.MySqlClient.MySqlPool.GetPooledConnection() +347
   MySql.Data.MySqlClient.MySqlPool.TryToGetDriver() +201
   MySql.Data.MySqlClient.MySqlPool.GetConnection() +125
   MySql.Data.MySqlClient.MySqlConnection.Open() +724
   MySql.Web.Security.MySQLMembershipProvider.GetUser(String username, Boolean userIsOnline) +120

[ProviderException: An exception occurred. Please check the Event Log.]
   MySql.Web.Security.MySQLMembershipProvider.GetUser(String username, Boolean userIsOnline) +380
   MySql.Web.Security.MySQLMembershipProvider.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) +357
   System.Web.UI.WebControls.CreateUserWizard.AttemptCreateUser() +318
   System.Web.UI.WebControls.CreateUserWizard.OnNextButtonClick(WizardNavigationEventArgs e) +102
   System.Web.UI.WebControls.Wizard.OnBubbleEvent(Object source, EventArgs e) +418
   System.Web.UI.WebControls.CreateUserWizard.OnBubbleEvent(Object source, EventArgs e) +161
   System.Web.UI.WebControls.WizardChildTable.OnBubbleEvent(Object source, EventArgs args) +19
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
   System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e) +118
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +166
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

When I run WSAT it says membership and role provider tests successfully connected to the server. I've checked and rechecked and the account in my connection string has full priviledges to the database. It won't even work if I run the root user account the server which I know has permissions.

You can see the Membership and role provider details in the web config and they look like what is int he connector documentation.

What am I not doing right here?


Good morning everybody.

I want to practise ASP.NET Authentication, and Authorization features in Visual Studio 2010.

I wanted to store user account information NOT IN THE aspnet db, but in a SEPARATE database. Hence, I have tried to use aspnet_regiis tool at visual studio command prompt. I am not presenting with wizard type window. Without wizard, I don't know how to store user information in a separate database otherthan aspnet db.

Can anybody please suggest any solution for this.

Also, one more thing:

It looks like lot of features have been changed in Visual Studio 2010 to work with Forms Authentication. If it is really changed, can anybody please suggest me the better resources to learn on the web?

Thansk in advance,
Ashok kumar.



   I need to look into the security of a folder of an application that was written by a previous programmer. I found it in VS.NET 2005 under

 the 'Website' tab -->ASP.NET Configuration and then clicked on Security tab on the page and then 'Create or Manage roles' link and then it displays the page with all the roles and at times it doesn't. Most of the time it is displaying the error page


Internet Explorer cannot display the webpage
  Most likely causes: You are not connected to the Internet. The website is encountering problems. There might be a typing error in the address.
  What you can try:
Diagnose Connection Problems
More informationMore information

This problem can be caused by a variety of issues, including:

Internet connectivity has been lost. The website is temporarily unavailable. The Domain Name Server (DNS) is not reachable. The Domain Name Server (DNS) does not have a listing for the website's domain. If this is an HTTPS (secure) address, click Tools, click Internet Options, click Advanced, and check to be sure the SSL and TLS protocols are enabled under the security section.

For offline users

You can still view subscribed feeds and some recently viewed webpages.
To view subscribed feeds

Click the Favorites Center button , click Feeds, and then click the feed you want to view.

To view recently visited webpages (might not work on all pages)

Click Tools , and then click Work Offline. Click the Favorites Center button , click History, and then click the page you want to view.


I have no idea why it is displaying this and how to fix it. Can some one please help to fix this page be able to manage the roles and users links on the Security page?

Thanks in advance,


Hello gurus!

Firstly I want to apologies if this question is out of place here.. if someone can direct me to the correct forumn great and Thanks!

I have a VB.NET application which uses its own Backend Database (MSSQL Server). I need to distribute this application to sites where there will be an existing SQL Server.

So I will need to Create the Database on this server. The Application includes methods for building the database on startup if not already connected to one.

However the users windows logon may not have the correct permission to connect and create a Database on the Server. I have a DB Setup form in my application which asks for the Servname, Username, Password and Database name. I have catered for Windows Authentication and SQL Server Authentication within the form - the user makes the choice.

Assuming they enter a Username and Password for SQL Server Athentication then I will be trying to connect using this user and create the database on the given server. The following is my outline logic:-

                                                                  Create db Process
                                                               Check Credentials
                                                                   /                 \
                                                 Dont Work /                    \ Work
                                                                /                       \
                                               Ask if Credentials                 \ 
                                              should be created?                 \
                                                        |                                  |
                                             Prompt for sa                     Create DB
                                                        |                                 Using
                                                        |                             Credentials
                                          Create DB Instance
                                                   using sa
                                            Create Credentials
                                         with New DB as default
                                                  using sa
                                          Generate DB Tables
                                           Using Credentials

So all clear on the western front!

I am using :-
Imports System.Data.Sql
Imports System.Data.SqlClient

What I need to know is how do I access Users to check roles on SQL Server? (Code Samples?)
How do I create the New user on the server and assign ownership of the new database to the new user?
Is this in fact the best method for achieving this?

Thanks in advance for any help forthcoming!
Perth in Western Australia!


Hi, following http://www.theproblemsolver.nl/usingthemembershipproviderinwinforms.htm I set up the membership & roles providers in app.config and try use it in code - with "<roleManager enabled="true"/>" in app.config, otherwise, error is thrown.

Authentication works well, but roles always returns empty roles array for connected user.

This part works:

If Membership.ValidateUser(userName, password) Then' Set the current application principal information to a known userDim identity As GenericIdentity
    Dim principal As RolePrincipal
    Dim user As MembershipUser

    user = Membership.GetUser(userName)
    identity = New GenericIdentity(user.UserName)
    principal = New RolePrincipal(identity)
    Threading.Thread.CurrentPrincipal = principal

This one doesn't:

If principal.IsInRole("Club") Then
      LoggedInUserRole = "Club"
      Return True
      Exit Function
    End If
No error is thrown though.

Similarly, if I try to add a user to a known, existing role, an exception is thrown :

If Not Roles.IsUserInRole(userName, "club") Then
      Roles.AddUserToRole(userName, "club")
    End If

Exception msg is: Cannot find role ''(I mean the role name isn't given back in exception.)

Any clue?

Please do not tell me to use Windows Client Administration within project services, I need my own SQL DB connection + the client app services is a bloated feature, bug prone.


So I have a set of 5 radio buttons corresponding to the roles a user can have on my website.  I have been successfully able to retreive what radio button needs to be checked for the role the user is currently in...

        string username = Request.QueryString["username"];
        // Get Access Levels and populate radio buttons.
        if (Roles.IsUserInRole(username, "Banned") == true)
            RadioButton4.Checked = true;
        if (Roles.IsUserInRole(username, "Member") == true)
            RadioButton1.Checked = true;
        if (Roles.IsUserInRole(username, "FOB_Employee") == true)
            RadioButton2.Checked = true;
        if (Roles.IsUserInRole(username, "FOB_Administrator") == true)
            RadioButton3.Checked = true;
        if (Roles.IsUserInRole(username, "Webmaster") == true)
            RadioButton5.Checked = true;

My problem is I do not know what to do with the actual procedure of changing the roles based on the new radio button selection.  I have tried many different methods, including using if statements to check if the user is currently in the role, remove him/her from that roll, and then add the user to the newly selected role.  It appears, from my testing, that you can not use a Roles.RemoveUserFromRole line with a User.AddUserToRole line at the same time (in the button OnClick event).  Do you have any suggestions on what to use for code?  Thank for your time, and if more explination is needed, please just ask.


Hello All,

I have a requirement where i need to access the methods of one user control in another user control.
Any pointers in this direction is greatly appreciated.

Thank you



I have an application of many pages of consultation and same time I have a module of adding users by roles and creating accounts by role.(the application is ready but i cant manage the roles)

the tutorials that i found are very useful to manage roles but its roles fixed before(administrators,supervisors)


 if I add a new role (agent) i want to grant to this new role a new access to pages(different access than admin and supervisor)

and disable new controls

why not using checkbox to every new role checking a field related to database

is it possible?if yes ,how can i begin?



SO. I have created several Roles and Memberships on my local copy of my web site.

If I use the local web site administration tool, the roles data appears to be stored in a SQL database called AspNetSqlProvider.

When I deploy o a remote site and try and log in with a role I get an error message...

The SSE Provider did not find the database file specified in the connection string. At the configured trust level (below High trust level), the SSE provider can not automatically create the database file.

I guess its looking for the AspNetSqlProvider database. 

Would I expect the hosting service to provide that database or do I need to create my own database within the web site ?

How do you change to another database ?




<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure