Search code examples
c#asp.net-coreauthorizationasp.net-identity

Role Based Authorization Identity API - registration not working


I have been following a Youtube video: https://www.youtube.com/watch?v=IBpZCFbjvA0 to use the identity API to create role-based users for my asp.net core web app. The role creates and stores successfully in my database but I get an error trying to register a user.

The error is: An unhandled exception occurred while processing the request. ArgumentNullException: Value cannot be null. Parameter name: items Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList..ctor(IEnumerable items, string dataValueField, string dataTextField, IEnumerable selectedValues, string dataGroupField).

I have a public github repository along with the full error in the readme. https://github.com/tripiod8/AUTHORIZATION_EXERCISE3.git

I'm new to learning ASP and I would really appreciate if anybody could explain to me why one of list fields is null.

Thank you very much!


Solution

  • The error is: An unhandled exception occurred while processing the request. ArgumentNullException: Value cannot be null. Parameter name: items Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList..ctor(IEnumerable items, string dataValueField, string dataTextField, IEnumerable selectedValues, string dataGroupField).

    That is because you do not set the data to selectlist in your post handler.

    Add the following code:

    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
        var role = _roleManager.FindByIdAsync(Input.Name).Result;
        if (ModelState.IsValid)
        {
            //...
    
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
        }
    
        ViewData["roles"] = _roleManager.Roles.ToList();
    
        return Page();
    }