Search code examples
c#asp.netasp.net-mvcasp.net-identity

Action passing null instead of string in asp.net mvc application


I am absolutely stuck on this, I have created an action to add a new Identity Role to my database using the Identity Framework. Unfortunately whenever it is executed, it returns that it has failed and after I inserted a breakpoint, I established that I am passing null as the value for newRole and not superadmin as would be expected.

The below is the URL I am using, exactly as I am using it:

https://localhost:44344/account/addrole/superadmin

And this is the corresponding action:

[Authorize(Roles = RoleNames.CanAddUsers)]
public ActionResult AddRole(string newRole)
{
    var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
    var roleManager = new RoleManager<IdentityRole>(roleStore);
    var result = roleManager.Create(new IdentityRole(newRole));

    return result.Succeeded 
        ? Content(newRole + " added to database.") 
        : Content("Failed to add " + newRole + ".");
}

Now I have checked and double checked that the user I am logged in as whilst testing this has the role CanAddUsers and I am not being redirected to login but simply receiving Failed to add .

To confirm, the following is my route and I cannot find anything else suggesting my code may be routed in a different manner.

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

I am sure at this point it is probably an incredibly obvious mistake but I cannot find it!

  • asp.net identity version: 2.2.1
  • asp.net mvc version: 5.2.3
  • entity framework 6.3.1

Solution

  • If you want to use the MapRoute only, then you should know that the name of the optional parameter (id in your case) will be used.

    Then you should either rename your Action's parameter to id, or explicitly say that you use the newRole variable by writing addrole?newRole=superadmin.

    Or else, as others pointed out, you may prefer to use POST instead of GET for this.