Reputation: 3511
I'm using ASP.NET Identity in my ASP.NET MVC app. My problem occures while adding user to role. There isn't any exception, but as a result of um.AddToRole() no db entry is added to AspNetUserRoles table. My action method looks like that:
public ActionResult GrantAdmin(string id)
{
ApplicationUser user = um.FindById(id);
if (!rm.RoleExists("admin"))
{
rm.Create(new IdentityRole("admin"));
}
um.AddToRole(user.Id, "admin");
return View((object)user.UserName);
}
um is an object of UserManager class:
private UserManager<ApplicationUser> um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
What can be a reason of that kind of application behavior? Any idea?
===EDIT=== It is my DbContext:
public ApplicationDbContext()
: base("DefaultConnection")
{
}
And Default Connection in Web.config:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-RecommendationPlatform-20140404055015.mdf;Initial Catalog=aspnet-RecommendationPlatform-20140404055015;Integrated Security=True" providerName="System.Data.SqlClient" />
Upvotes: 3
Views: 2373
Reputation: 23571
When working with ASP.NET Identity it is important to remember that many operations return a result object where eventual errors are stored. There are no exceptions. Therefore one should check the result object for success after every operation. This is true not only for roles but for most methods that save data to the database. Even if it works you should still test for success and eventually throw an exception if the result is not success.
As per the comments in your case the problem was invalid username.
Upvotes: 5