Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I am new to MVC and I am trying to add a user to a role after login.

I have managed to use the AuthorizeRoles on actions in a controller but when trying to add a user to a like as per the below code I get an error saying User Not Found.

C#
System.Web.Security.Roles.AddUsersToRole(new string[] { httpContext.User.Identity.Name }, roles);


The Users Table in my database is as follows:
C#
[Id]
      ,[FirstName]
      ,[LastName]
      ,[EmailAddress]
      ,[UserName]
      ,[Password]
      ,[DateCreated]
      ,[Gender]
      ,[ApplicationId]
      ,[IsAnonymous]
      ,[LastActivityDate]
      ,[UserId]


I have tried passing through the UserName, UserId and email address of any user but it keeps telling me user not found for any user that has been logged in.

In my web.config I am using the below configuration in System.Web:
<rolemanager enabled="true" defaultprovider="SqlRoleProvider">
<providers>
<clear>
<add name="SqlRoleProvider">
connectionStringName="RolesCon"
applicationName="/"
type="System.Web.Providers.DefaultRoleProvider"/>



Has anyone else experienced this type of an issue?

What I have tried:

Searched Google, added rolemanager to the web.config file.
Posted
Updated 8-Aug-16 23:28pm
v4

1 solution

Hi I imagine that
SQL
httpContext.User.Identity

is not being set to the logged in user.
You need to make sure that in your application some code is setting it to correct value.
An example is to use FormsAuthentication to set the cookie and configure FormsAuthentication in web.config for it to work.
 
Share this answer
 
Comments
Kats2512 9-Aug-16 5:31am    
I have done that, when I use httpContext.User.Identity.Name.ToString() it does return the name that I am logged in as.
Kats2512 14-Aug-16 5:44am    
Thanks for trying but I eventually created my own static method since I figured I am using a custom database and not the usual asp.net identity database with their tables.

What I did is now working :)
njammy 15-Aug-16 6:20am    
I think everyone will agree that you should have mentioned your custom database in the first line of your question as it's pretty important.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900