AddToRole() method doesn't result in db entry in ASP.NET Identity

两盒软妹~` 提交于 2019-12-14 01:26:42

问题


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" />

回答1:


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.



来源:https://stackoverflow.com/questions/24352361/addtorole-method-doesnt-result-in-db-entry-in-asp-net-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!