In the background of my mvc 4 application i am running a scheduler that does some tasks. When i want to get the roles from a specific user the functions returns a nullreference exception.
An unhandled exception of type 'System.NullReferenceException' occurred in System.Web.dll
The function does work with a normal request, but not outside a normal http request.
Why is GetRolesForUser not working outside a normal request (assuming that is the problem) and how can i fix it?
Note: Im using the parameter username, the user exists and has a role.
Im using the DefaultMembershipProvider.
Code:
public static string GetUserRoleByUsername(string username)
{
return System.Web.Security.Roles.GetRolesForUser(username).First();
}
Thanks in advance!
Edit:
I have fixed it by initializing the roleProvider, i am not sure why i need to initialize it. Any ideas why i have to do this?
var roleProvider = System.Web.Security.Roles.Provider;