基于角色的授权身份API-注册不起作用

时间:2020-04-14 18:53:19

标签: c# asp.net-core authorization asp.net-identity

我一直在关注YouTube视频:https://www.youtube.com/watch?v=IBpZCFbjvA0 使用身份API为asp.net核心Web应用创建基于角色的用户。该角色成功创建并存储在我的数据库中,但是尝试注册用户时出现错误。

错误是: 处理请求时发生未处理的异常。 ArgumentNullException:值不能为null。参数名称:项目Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList..ctor(IEnumerable项目,字符串dataValueField,字符串dataTextField,IEnumerable selectedValues,字符串dataGroupField)。

我有一个公共github存储库,以及自述文件中的完整错误。 https://github.com/tripiod8/AUTHORIZATION_EXERCISE3.git

我是学习ASP的新手,如果有人可以向我解释为什么列表字段之一为空,我将不胜感激。

非常感谢您!

1 个答案:

答案 0 :(得分:1)

错误是:处理请求时发生未处理的异常。 ArgumentNullException:值不能为null。参数名称:项目Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList..ctor(IEnumerable项目,字符串dataValueField,字符串dataTextField,IEnumerable selectedValues,字符串dataGroupField)。

这是因为您没有在后处理程序中将数据设置为selectlist。

添加以下代码:

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();
}