8

I have an ASP.NET application that uses the Roles.GetRolesForUser method. The call work fines within the application, but when i use the same call in a referenced library, it throws an exception. The exception message is:

Object reference not set to an instance of an object

The strange things is that when i check Roles, it is instantiated.

My code looks like this:

var roles = Roles.GetRolesForUser(userName);

Any suggestions?

John Saunders
  • 157,405
  • 24
  • 229
  • 388
jason
  • 91
  • 1
  • 4
  • Ok apparently if you calling Roles.GetRolesForUser in a referenced library, you have to use it as follows: var Roles = Roles.Provider.GetRolesForUser(userName); Notice the difference, explicitly calling the Provider on Roles – jason Nov 06 '13 at 08:13
  • 4
    Add this as an answer and mark it as accepted, so another user looking for this finds it easier. – danielrozo Nov 06 '13 at 08:23
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Jun 17 '14 at 15:16
  • @JohnSaunders You are right, but this is very exceptional status, which the exception here is .NET Bug – Hakan Fıstık May 17 '17 at 11:58

2 Answers2

6

NOTE: according to the OP's comment himself, this answer solved his problem.

This is a .NET bug.
To solve this issue call:

string[] roles = Roles.Provider.GetRolesForUser(userName);

here is a very similar question.

Hakan Fıstık
  • 11,376
  • 8
  • 74
  • 105
  • 1
    The cause for me was that MSDTC was not running. The above fix got the code working even when MSDTC was still off. – Savage Nov 22 '17 at 14:07
0

In MVC 5 you can get user roles with GetRoles(Id) method.
But, before use GetRoles you have to make userManager object:

var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

var d = userManager.GetRoles(5);
Hakan Fıstık
  • 11,376
  • 8
  • 74
  • 105
MortezaDalil
  • 342
  • 1
  • 2
  • 14