试图显示列出所有行 MVC 6 的简单视图

Trying to display simple View listing all the rows MVC 6

我收到这个奇怪的错误: MissingMethodException: 无法创建接口实例。

我已经使我的对象尽可能简单,只是试图掌握与此角色管理一起工作的东西。

MVC 6 应用程序适用于单个用户的注册和登录。我什至可以创建角色并在启动时分配它们。但任何尝试做任何其他事情都让我受挫。我只是想显示一个角色列表。

控制器:

namespace MVC6.Controllers
{

    //[Authorize(Roles = Utilities.Security.AdminRole)]
    public class RolesManagementController : Controller
    {

        // GET: /RolesManagement/

        public ActionResult Index(IServiceProvider serviceProvider)
        {
            var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

          return View(RoleManager.Roles.ToList());

        }

简单索引视图:

@model List<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>



@{
    ViewBag.Title = "Roles";
}


<h2>@ViewBag.Title</h2>

<br /><br />

<fieldset>
    <table id="roles" class="display">

        <thead>
            <tr>
                <th width="20%">Role Name</th>
                <th width="20%">Action</th>
            </tr>
        </thead>
        <tbody>
            @if (null != Model)
            {
                foreach (var role in Model)
                {
                    <tr>
                        <td>
                            @role.Name
                        </td>
                        <td>

                        </td>
                    </tr>
                }
            }
        </tbody>
    </table>
</fieldset>

我使用 ActionResult 内部的一个断点在调试中启动应用程序,只是为了看看,它从未遇到断点并且 returns 这个错误:

MissingMethodException: 无法创建接口实例。

当我在 URL.

中键入“http://localhost:61849/RolesManagement”时,我什么也没得到,空白,空虚

只要你想将依赖项直接注入到操作方法中,就需要使用 [FromServices] 属性。检查 asp docs:

Sometimes you don’t need a service for more than one action within your controller. In this case, it may make sense to inject the service as a parameter to the action method. This is done by marking the parameter with the attribute [FromServices]

因此您的代码如下所示:

public ActionResult Index([FromServices]IServiceProvider serviceProvider)
{
    var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
    var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
  return View(RoleManager.Roles.ToList());
}

您可能还想更改您的控制器,以便在构造函数中提供这些依赖项(在这种情况下您不需要该属性)。恕我直言,那会更干净。