No ApplicationRoleManager class in my MVC 5 templa

2019-04-06 18:19发布

问题:

When I try to add app.CreatePerOwinContext(ApplicationRoleManager.Create) to configauth I am told applicationRoleManager does not exist. Does anybody know why?

using Microsoft.Owin.Security.OAuth;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.Owin.Security.Google;
using Owin;
using System;
using LaCeibaNetv4.Models;

namespace LaCeibaNetv4
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

回答1:

I was having the same issue and came across this code which I used to add the class to my project:

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole,string> roleStore)
    : base(roleStore) { }

    public static ApplicationRoleManager Create(
        IdentityFactoryOptions<ApplicationRoleManager> options, 
        IOwinContext context)
    {
        var manager = new ApplicationRoleManager(
            new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
        return manager;
    }
}

Also, remember to have it configured at startup by adding this piece of code in Startup.Auth.cs:

app.CreatePerOwinContext<ApplicationRoleManager>(Application‌​RoleManager.Create); 

The full article is available here: http://www.codeproject.com/Articles/762428/ASP-NET-MVC-and-Identity-Understanding-the-Basics