我正在尝试将用户注册到角色,但出现以下错误:
No user found was found that has the name "MyName"
我使用默认模板创建了一个 MVC 4 应用程序。
我创建了一个自定义成员资格提供程序并实现了 CreateUser 方法,如下所示
public User CreateUser(User i_userToCreate)
{
using (var _db = new Repository())
{
User _user = _db.CreateUser(i_userToCreate);
MembershipUser _membershipUser = new MembershipUser(providerName: "ATWMembershipProvider",
name: _user.UserName,
providerUserKey: null,
email: _user.Email,
passwordQuestion: "",
comment: "",
isApproved: true,
isLockedOut: false,
creationDate: DateTime.UtcNow,
lastLoginDate: DateTime.UtcNow,
lastActivityDate: DateTime.UtcNow,
lastPasswordChangedDate: DateTime.UtcNow,
lastLockoutDate: DateTime.UtcNow);
return _user;
}
这就是我配置 web.config 的方式
<appSettings>
<add key="enableSimpleMembership" value="false"/>
<add key="autoFormsAuthentication" value="false"/>
</appSettings>
<system.web>
<membership defaultProvider="ATWMembershipProvider">
<providers>
<clear/>
<add name="ATWMembershipProvider" type="AroundTheWorld.Infrastructure.ATWMembershipProvider"
enablePasswordRetrieval="false"
ConnetionStringName="Context"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
equiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10" applicationName="myApplication" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">
<providers>
<remove name="AspNetSqlRoleProvider" />
<add name="AspNetSqlRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<!-- note: WebMatrix registers SimpleRoleProvider with name
'AspNetSqlRoleProvider'. I don't know why but i kept it. -->
</providers>
</roleManager>
现在验证方法如下:
var MembershipProvider = new ATWMembershipProvider();
User authentictedUser = MembershipProvider.CreateUser(_userToCreate);
FormsAuthentication.SetAuthCookie(authentictedUser.UserName, true);
System.Web.Security.Roles.AddUserToRole(authentictedUser.UserName, authentictedUser.Role.Name);
Session.Add("UserID", authentictedUser.ID);
Session.Add("UserName", authentictedUser.UserName);
我已经检查了以下内容:
- 我的用户作为所有必要信息
- 我在 App_start "user" , "admin" 中注册了两个角色
但我仍然收到一个错误,即未找到名为“MyName”的用户
在不需要基于角色保护文件夹的 asp Web 表单中
我要做的就是将控制器内的动作保护到特定的“角色”
[Authorize(Roles = "admin")]
public ActionResult GetAllLocations()
{
using (var _db = new Repository())
{
return View(_db.GetLocations());
}
}