我在mvc 4应用程序中添加新角色...但每次都会出现此错误
这是我的注册方法
//
// POST: /Account/Register
[AllowAnonymous]
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
object x = Membership.GetUser(model.UserName);
if (Membership.GetUser(model.UserName) == null)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null,
out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
Roles.AddUserToRole(model.UserName, model.Role);
//model.Role is the DropDown Selected Text.. its value is 'Admin'
FormsAuthentication.SetAuthCookie(model.UserName,
false /* createPersistentCookie */);
return RedirectToAction("Index", "EUT");
}
else
{
ModelState.AddModelError("",
ErrorCodeToString(createStatus));
}
}
else
{
ModelState.AddModelError("", "User Already exists");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
在我的Web配置中
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider"
cacheRolesInCookie="true"
cookieName=".myroles"
cookieTimeout="30"
cookieSlidingExpiration="true"
cookieProtection="All">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
我看过类似的帖子:
Add User Roles on Registration (Forms Authentication) MVC3
Adding users to roles on registring failed ASP.NET MVC3
Adding roles only adding one to user
尝试将所选值与模型属性绑定...仍然无效...
任何建议都会有所帮助
答案 0 :(得分:0)
您可以检查角色是否存在,如果不是这样,则添加它:
var adminRoleExists = Roles.RoleExists(AppRoles.Admin.ToString());
if (!adminRoleExists)
{
Roles.CreateRole(AppRoles.Admin.ToString());
}