This just happened to me a while ago. In my code, I need to get the Roles
that a specified user in assigned in.
here is what's in my code:
string[] roles = {};
SqlRoleProvider fxSRP = new SqlRoleProvider();
string id = Request.QueryString["UserName"] as string;
string userName = id;
now this is all fine, but when I get to this bit:
roles = fxSRP.GetRolesForUser(userName);
The system throws that godforsaken Object reference not set to an instance of an object
exception. Has driven me nuts for a few minutes, honestly. but, when I change that small bit of code to this (this is an explicit call, right?) :
roles = Roles.GetRolesForUser(userName);
The code works. I'm able to retrive the Roles
for the user and use them however I want.
I want to know, why is it that using the GetRolesForUser
from the instatiated SqlRoleProvider
doesn't work? Because this might also happen for the next bit of code that I will work on, which is to use RemoveUsersFromRoles
and AddUsersToRoles
. And also, what kind of instance is the program looking for? What have I not instantiated for the method to work?
You're calling
new SqlRoleProvider()
, but according to the documentation for that constructor, http://msdn.microsoft.com/en-us/library/system.web.security.sqlroleprovider.sqlroleprovider.aspx:(Emphasis mine.) I'm not an expert on this class, but I think this remark indicates that you shouldn't try to do that.