سلام
من در areaمربوط به Admonstrator یک کنترلر دارم که می خوام ادمین بتونه نقش های جدیدی رو ایجاد ،حذف،ویرایش و... بکنه
کدهای مربوط به کنترلر:RoleAdminController
using SafarName.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.AspNet.Identity.EntityFramework; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Collections.Generic; namespace SafarName.Areas.Adminstrator.Controllers { public class RolesAdminController:Controller { public RolesAdminController() { } public RolesAdminController(ApplicationUserManager userManager, ApplicationRoleManager roleManager) { UserManager = userManager; RoleManager = roleManager; } /// <summary> /// این قسمت برای این است که چه یوزر هایی داریم /// </summary> private ApplicationUserManager _userManager; public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } set { _userManager = value; } } /// <summary> /// این قسمت برای این است که چه رول هایی داریم /// </summary> private ApplicationRoleManager _roleManager; public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); } private set { _roleManager = value; } } // // GET: /Roles/ public ActionResult Index() { return View(RoleManager.Roles); } // // GET: /Roles/Details/5 public async Task<ActionResult> Details(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var role = await RoleManager.FindByIdAsync(id); // Get the list of Users in this Role var users = new List<ApplicationUser>(); // Get the list of Users in this Role foreach (var user in UserManager.Users.ToList()) { if (await UserManager.IsInRoleAsync(user.Id, role.Name)) { users.Add(user); } } ViewBag.Users = users; ViewBag.UserCount = users.Count(); return View(role); } // // GET: /Roles/Create public ActionResult Create() { return View(); } // // POST: /Roles/Create [HttpPost] public async Task<ActionResult> Create(RoleViewModel roleViewModel) { if (ModelState.IsValid) { var role = new IdentityRole(roleViewModel.Name); var roleresult = await RoleManager.CreateAsync(role); if (!roleresult.Succeeded) { ModelState.AddModelError("", roleresult.Errors.First()); return View(); } return RedirectToAction("Index"); } return View(); } // // GET: /Roles/Edit/Admin public async Task<ActionResult> Edit(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var role = await RoleManager.FindByIdAsync(id); if (role == null) { return HttpNotFound(); } RoleViewModel roleModel = new RoleViewModel { Id = role.Id, Name = role.Name }; return View(roleModel); } // // POST: /Roles/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "Name,Id")] RoleViewModel roleModel) { if (ModelState.IsValid) { var role = await RoleManager.FindByIdAsync(roleModel.Id); role.Name = roleModel.Name; await RoleManager.UpdateAsync(role); return RedirectToAction("Index"); } return View(); } // // GET: /Roles/Delete/5 public async Task<ActionResult> Delete(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var role = await RoleManager.FindByIdAsync(id); if (role == null) { return HttpNotFound(); } return View(role); } // // POST: /Roles/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<ActionResult> DeleteConfirmed(string id, string deleteUser) { if (ModelState.IsValid) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var role = await RoleManager.FindByIdAsync(id); if (role == null) { return HttpNotFound(); } IdentityResult result; if (deleteUser != null) { result = await RoleManager.DeleteAsync(role); } else { result = await RoleManager.DeleteAsync(role); } if (!result.Succeeded) { ModelState.AddModelError("", result.Errors.First()); return View(); } return RedirectToAction("Index"); } return View(); } } }
ونیز کدهای مربوط به IdentityConfig
public class ApplicationRoleManager : RoleManager<IdentityRole> { public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore) : base(roleStore) { } public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context) { return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>())); } }
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
موقع ایجاد کردن نقش جدید به کد
var roleresult = await RoleManager.CreateAsync(role);
خطا میده که عکس خطا رو پایین قرار میدم
وتوی index هم دوباره به کد
return View(RoleManager.Roles);
همین خطا رو میده
اگه میشه لطف کنین بررسی کنین که مشکل کجاست
موقعی که پروژه ی جدید ایجاد میکنم توی IdentityConfigکلاس applicationRoleManaggerرو ندارم واون کلاسApplicationRoleManagerرو که بالا گذاشتم خودم به identityConfig اضافه کردم به نظرتون میشه مشکل از اینجا
باشه که نقش های دیتابیس رو واسم نمییاره؟
مشکلم حل شد
مشکل اینجا بود که applicationaraoleManagerرو توی Startup.Auth.csهم باید Create می کردم که نکرده بودم
هیچ کاربری تا کنون از این پست تشکر نکرده است
با ما تماس بگیرید تا در این مسیر همراهتان باشیم :)